clang 23.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"
56#include "clang/Basic/LLVM.h"
58#include "clang/Basic/Linkage.h"
59#include "clang/Basic/Module.h"
69#include "llvm/ADT/APFixedPoint.h"
70#include "llvm/ADT/APInt.h"
71#include "llvm/ADT/APSInt.h"
72#include "llvm/ADT/ArrayRef.h"
73#include "llvm/ADT/DenseMap.h"
74#include "llvm/ADT/DenseSet.h"
75#include "llvm/ADT/FoldingSet.h"
76#include "llvm/ADT/PointerUnion.h"
77#include "llvm/ADT/STLExtras.h"
78#include "llvm/ADT/SmallPtrSet.h"
79#include "llvm/ADT/SmallVector.h"
80#include "llvm/ADT/StringExtras.h"
81#include "llvm/ADT/StringRef.h"
82#include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
83#include "llvm/Support/Capacity.h"
84#include "llvm/Support/Casting.h"
85#include "llvm/Support/Compiler.h"
86#include "llvm/Support/ErrorHandling.h"
87#include "llvm/Support/MD5.h"
88#include "llvm/Support/MathExtras.h"
89#include "llvm/Support/SipHash.h"
90#include "llvm/Support/raw_ostream.h"
91#include "llvm/TargetParser/AArch64TargetParser.h"
92#include "llvm/TargetParser/Triple.h"
93#include <algorithm>
94#include <cassert>
95#include <cstddef>
96#include <cstdint>
97#include <cstdlib>
98#include <map>
99#include <memory>
100#include <optional>
101#include <string>
102#include <tuple>
103#include <utility>
104
105using namespace clang;
106
117
118/// \returns The locations that are relevant when searching for Doc comments
119/// related to \p D.
122 assert(D);
123
124 // User can not attach documentation to implicit declarations.
125 if (D->isImplicit())
126 return {};
127
128 // User can not attach documentation to implicit instantiations.
129 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
130 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
131 return {};
132 }
133
134 if (const auto *VD = dyn_cast<VarDecl>(D)) {
135 if (VD->isStaticDataMember() &&
136 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
137 return {};
138 }
139
140 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
141 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
142 return {};
143 }
144
145 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
146 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
147 if (TSK == TSK_ImplicitInstantiation ||
148 TSK == TSK_Undeclared)
149 return {};
150 }
151
152 if (const auto *ED = dyn_cast<EnumDecl>(D)) {
153 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
154 return {};
155 }
156 if (const auto *TD = dyn_cast<TagDecl>(D)) {
157 // When tag declaration (but not definition!) is part of the
158 // decl-specifier-seq of some other declaration, it doesn't get comment
159 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
160 return {};
161 }
162 // TODO: handle comments for function parameters properly.
163 if (isa<ParmVarDecl>(D))
164 return {};
165
166 // TODO: we could look up template parameter documentation in the template
167 // documentation.
171 return {};
172
174 // Find declaration location.
175 // For Objective-C declarations we generally don't expect to have multiple
176 // declarators, thus use declaration starting location as the "declaration
177 // location".
178 // For all other declarations multiple declarators are used quite frequently,
179 // so we use the location of the identifier as the "declaration location".
180 SourceLocation BaseLocation;
184 // Allow association with Y across {} in `typedef struct X {} Y`.
186 BaseLocation = D->getBeginLoc();
187 else
188 BaseLocation = D->getLocation();
189
190 if (!D->getLocation().isMacroID()) {
191 Locations.emplace_back(BaseLocation);
192 } else {
193 const auto *DeclCtx = D->getDeclContext();
194
195 // When encountering definitions generated from a macro (that are not
196 // contained by another declaration in the macro) we need to try and find
197 // the comment at the location of the expansion but if there is no comment
198 // there we should retry to see if there is a comment inside the macro as
199 // well. To this end we return first BaseLocation to first look at the
200 // expansion site, the second value is the spelling location of the
201 // beginning of the declaration defined inside the macro.
202 if (!(DeclCtx &&
203 Decl::castFromDeclContext(DeclCtx)->getLocation().isMacroID())) {
204 Locations.emplace_back(SourceMgr.getExpansionLoc(BaseLocation));
205 }
206
207 // We use Decl::getBeginLoc() and not just BaseLocation here to ensure that
208 // we don't refer to the macro argument location at the expansion site (this
209 // can happen if the name's spelling is provided via macro argument), and
210 // always to the declaration itself.
211 Locations.emplace_back(SourceMgr.getSpellingLoc(D->getBeginLoc()));
212 }
213
214 return Locations;
215}
216
218 const Decl *D, const SourceLocation RepresentativeLocForDecl,
219 const std::map<unsigned, RawComment *> &CommentsInTheFile) const {
220 // If the declaration doesn't map directly to a location in a file, we
221 // can't find the comment.
222 if (RepresentativeLocForDecl.isInvalid() ||
223 !RepresentativeLocForDecl.isFileID())
224 return nullptr;
225
226 // If there are no comments anywhere, we won't find anything.
227 if (CommentsInTheFile.empty())
228 return nullptr;
229
230 // Decompose the location for the declaration and find the beginning of the
231 // file buffer.
232 const FileIDAndOffset DeclLocDecomp =
233 SourceMgr.getDecomposedLoc(RepresentativeLocForDecl);
234
235 // Slow path.
236 auto OffsetCommentBehindDecl =
237 CommentsInTheFile.lower_bound(DeclLocDecomp.second);
238
239 // First check whether we have a trailing comment.
240 if (OffsetCommentBehindDecl != CommentsInTheFile.end()) {
241 RawComment *CommentBehindDecl = OffsetCommentBehindDecl->second;
242 if ((CommentBehindDecl->isDocumentation() ||
243 LangOpts.CommentOpts.ParseAllComments) &&
244 CommentBehindDecl->isTrailingComment() &&
247
248 // Check that Doxygen trailing comment comes after the declaration, starts
249 // on the same line and in the same file as the declaration.
250 if (SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second) ==
251 Comments.getCommentBeginLine(CommentBehindDecl, DeclLocDecomp.first,
252 OffsetCommentBehindDecl->first)) {
253 return CommentBehindDecl;
254 }
255 }
256 }
257
258 // The comment just after the declaration was not a trailing comment.
259 // Let's look at the previous comment.
260 if (OffsetCommentBehindDecl == CommentsInTheFile.begin())
261 return nullptr;
262
263 auto OffsetCommentBeforeDecl = --OffsetCommentBehindDecl;
264 RawComment *CommentBeforeDecl = OffsetCommentBeforeDecl->second;
265
266 // Check that we actually have a non-member Doxygen comment.
267 if (!(CommentBeforeDecl->isDocumentation() ||
268 LangOpts.CommentOpts.ParseAllComments) ||
269 CommentBeforeDecl->isTrailingComment())
270 return nullptr;
271
272 // Decompose the end of the comment.
273 const unsigned CommentEndOffset =
274 Comments.getCommentEndOffset(CommentBeforeDecl);
275
276 // Get the corresponding buffer.
277 bool Invalid = false;
278 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
279 &Invalid).data();
280 if (Invalid)
281 return nullptr;
282
283 // Extract text between the comment and declaration.
284 StringRef Text(Buffer + CommentEndOffset,
285 DeclLocDecomp.second - CommentEndOffset);
286
287 // There should be no other declarations or preprocessor directives between
288 // comment and declaration.
289 if (Text.find_last_of(";{}#@") != StringRef::npos)
290 return nullptr;
291
292 return CommentBeforeDecl;
293}
294
296 const auto DeclLocs = getDeclLocsForCommentSearch(D, SourceMgr);
297
298 for (const auto DeclLoc : DeclLocs) {
299 // If the declaration doesn't map directly to a location in a file, we
300 // can't find the comment.
301 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
302 continue;
303
305 ExternalSource->ReadComments();
306 CommentsLoaded = true;
307 }
308
309 if (Comments.empty())
310 continue;
311
312 const FileID File = SourceMgr.getDecomposedLoc(DeclLoc).first;
313 if (!File.isValid())
314 continue;
315
316 const auto CommentsInThisFile = Comments.getCommentsInFile(File);
317 if (!CommentsInThisFile || CommentsInThisFile->empty())
318 continue;
319
320 if (RawComment *Comment =
321 getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile))
322 return Comment;
323 }
324
325 return nullptr;
326}
327
329 assert(LangOpts.RetainCommentsFromSystemHeaders ||
330 !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin()));
331 Comments.addComment(RC, LangOpts.CommentOpts, BumpAlloc);
332}
333
335 const Decl *D,
336 const Decl **OriginalDecl) const {
337 if (!D) {
338 if (OriginalDecl)
339 OriginalDecl = nullptr;
340 return nullptr;
341 }
342
343 D = &adjustDeclToTemplate(*D);
344
345 // Any comment directly attached to D?
346 {
347 auto DeclComment = DeclRawComments.find(D);
348 if (DeclComment != DeclRawComments.end()) {
349 if (OriginalDecl)
350 *OriginalDecl = D;
351 return DeclComment->second;
352 }
353 }
354
355 // Any comment attached to any redeclaration of D?
356 const Decl *CanonicalD = D->getCanonicalDecl();
357 if (!CanonicalD)
358 return nullptr;
359
360 {
361 auto RedeclComment = RedeclChainComments.find(CanonicalD);
362 if (RedeclComment != RedeclChainComments.end()) {
363 if (OriginalDecl)
364 *OriginalDecl = RedeclComment->second;
365 auto CommentAtRedecl = DeclRawComments.find(RedeclComment->second);
366 assert(CommentAtRedecl != DeclRawComments.end() &&
367 "This decl is supposed to have comment attached.");
368 return CommentAtRedecl->second;
369 }
370 }
371
372 // Any redeclarations of D that we haven't checked for comments yet?
373 const Decl *LastCheckedRedecl = [&]() {
374 const Decl *LastChecked = CommentlessRedeclChains.lookup(CanonicalD);
375 bool CanUseCommentlessCache = false;
376 if (LastChecked) {
377 for (auto *Redecl : CanonicalD->redecls()) {
378 if (Redecl == D) {
379 CanUseCommentlessCache = true;
380 break;
381 }
382 if (Redecl == LastChecked)
383 break;
384 }
385 }
386 // FIXME: This could be improved so that even if CanUseCommentlessCache
387 // is false, once we've traversed past CanonicalD we still skip ahead
388 // LastChecked.
389 return CanUseCommentlessCache ? LastChecked : nullptr;
390 }();
391
392 for (const Decl *Redecl : D->redecls()) {
393 assert(Redecl);
394 // Skip all redeclarations that have been checked previously.
395 if (LastCheckedRedecl) {
396 if (LastCheckedRedecl == Redecl) {
397 LastCheckedRedecl = nullptr;
398 }
399 continue;
400 }
401 const RawComment *RedeclComment = getRawCommentForDeclNoCache(Redecl);
402 if (RedeclComment) {
403 cacheRawCommentForDecl(*Redecl, *RedeclComment);
404 if (OriginalDecl)
405 *OriginalDecl = Redecl;
406 return RedeclComment;
407 }
408 CommentlessRedeclChains[CanonicalD] = Redecl;
409 }
410
411 if (OriginalDecl)
412 *OriginalDecl = nullptr;
413 return nullptr;
414}
415
417 const RawComment &Comment) const {
418 assert(Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
419 DeclRawComments.try_emplace(&OriginalD, &Comment);
420 const Decl *const CanonicalDecl = OriginalD.getCanonicalDecl();
421 RedeclChainComments.try_emplace(CanonicalDecl, &OriginalD);
422 CommentlessRedeclChains.erase(CanonicalDecl);
423}
424
425static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
427 const DeclContext *DC = ObjCMethod->getDeclContext();
428 if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) {
429 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
430 if (!ID)
431 return;
432 // Add redeclared method here.
433 for (const auto *Ext : ID->known_extensions()) {
434 if (ObjCMethodDecl *RedeclaredMethod =
435 Ext->getMethod(ObjCMethod->getSelector(),
436 ObjCMethod->isInstanceMethod()))
437 Redeclared.push_back(RedeclaredMethod);
438 }
439 }
440}
441
443 const Preprocessor *PP) {
444 if (Comments.empty() || Decls.empty())
445 return;
446
447 FileID File;
448 for (const Decl *D : Decls) {
449 if (D->isInvalidDecl())
450 continue;
451
452 D = &adjustDeclToTemplate(*D);
453 SourceLocation Loc = D->getLocation();
454 if (Loc.isValid()) {
455 // See if there are any new comments that are not attached to a decl.
456 // The location doesn't have to be precise - we care only about the file.
457 File = SourceMgr.getDecomposedLoc(Loc).first;
458 break;
459 }
460 }
461
462 if (File.isInvalid())
463 return;
464
465 auto CommentsInThisFile = Comments.getCommentsInFile(File);
466 if (!CommentsInThisFile || CommentsInThisFile->empty() ||
467 CommentsInThisFile->rbegin()->second->isAttached())
468 return;
469
470 // There is at least one comment not attached to a decl.
471 // Maybe it should be attached to one of Decls?
472 //
473 // Note that this way we pick up not only comments that precede the
474 // declaration, but also comments that *follow* the declaration -- thanks to
475 // the lookahead in the lexer: we've consumed the semicolon and looked
476 // ahead through comments.
477 for (const Decl *D : Decls) {
478 assert(D);
479 if (D->isInvalidDecl())
480 continue;
481
482 D = &adjustDeclToTemplate(*D);
483
484 if (DeclRawComments.count(D) > 0)
485 continue;
486
487 const auto DeclLocs = getDeclLocsForCommentSearch(D, SourceMgr);
488
489 for (const auto DeclLoc : DeclLocs) {
490 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
491 continue;
492
493 if (RawComment *const DocComment = getRawCommentForDeclNoCacheImpl(
494 D, DeclLoc, *CommentsInThisFile)) {
495 cacheRawCommentForDecl(*D, *DocComment);
496 comments::FullComment *FC = DocComment->parse(*this, PP, D);
497 ParsedComments[D->getCanonicalDecl()] = FC;
498 break;
499 }
500 }
501 }
502}
503
505 const Decl *D) const {
506 auto *ThisDeclInfo = new (*this) comments::DeclInfo;
507 ThisDeclInfo->CommentDecl = D;
508 ThisDeclInfo->IsFilled = false;
509 ThisDeclInfo->fill();
510 ThisDeclInfo->CommentDecl = FC->getDecl();
511 if (!ThisDeclInfo->TemplateParameters)
512 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
514 new (*this) comments::FullComment(FC->getBlocks(),
515 ThisDeclInfo);
516 return CFC;
517}
518
521 return RC ? RC->parse(*this, nullptr, D) : nullptr;
522}
523
525 const Decl *D,
526 const Preprocessor *PP) const {
527 if (!D || D->isInvalidDecl())
528 return nullptr;
529 D = &adjustDeclToTemplate(*D);
530
531 const Decl *Canonical = D->getCanonicalDecl();
532 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
533 ParsedComments.find(Canonical);
534
535 if (Pos != ParsedComments.end()) {
536 if (Canonical != D) {
537 comments::FullComment *FC = Pos->second;
539 return CFC;
540 }
541 return Pos->second;
542 }
543
544 const Decl *OriginalDecl = nullptr;
545
546 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
547 if (!RC) {
550 const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
551 if (OMD && OMD->isPropertyAccessor())
552 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
553 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
554 return cloneFullComment(FC, D);
555 if (OMD)
556 addRedeclaredMethods(OMD, Overridden);
557 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
558 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
559 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
560 return cloneFullComment(FC, D);
561 }
562 else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
563 // Attach any tag type's documentation to its typedef if latter
564 // does not have one of its own.
565 QualType QT = TD->getUnderlyingType();
566 if (const auto *TT = QT->getAs<TagType>())
567 if (comments::FullComment *FC = getCommentForDecl(TT->getDecl(), PP))
568 return cloneFullComment(FC, D);
569 }
570 else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
571 while (IC->getSuperClass()) {
572 IC = IC->getSuperClass();
574 return cloneFullComment(FC, D);
575 }
576 }
577 else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) {
578 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
580 return cloneFullComment(FC, D);
581 }
582 else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
583 if (!(RD = RD->getDefinition()))
584 return nullptr;
585 // Check non-virtual bases.
586 for (const auto &I : RD->bases()) {
587 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
588 continue;
589 QualType Ty = I.getType();
590 if (Ty.isNull())
591 continue;
593 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
594 continue;
595
597 return cloneFullComment(FC, D);
598 }
599 }
600 // Check virtual bases.
601 for (const auto &I : RD->vbases()) {
602 if (I.getAccessSpecifier() != AS_public)
603 continue;
604 QualType Ty = I.getType();
605 if (Ty.isNull())
606 continue;
607 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
608 if (!(VirtualBase= VirtualBase->getDefinition()))
609 continue;
611 return cloneFullComment(FC, D);
612 }
613 }
614 }
615 return nullptr;
616 }
617
618 // If the RawComment was attached to other redeclaration of this Decl, we
619 // should parse the comment in context of that other Decl. This is important
620 // because comments can contain references to parameter names which can be
621 // different across redeclarations.
622 if (D != OriginalDecl && OriginalDecl)
623 return getCommentForDecl(OriginalDecl, PP);
624
625 comments::FullComment *FC = RC->parse(*this, PP, D);
626 ParsedComments[Canonical] = FC;
627 return FC;
628}
629
630void ASTContext::CanonicalTemplateTemplateParm::Profile(
631 llvm::FoldingSetNodeID &ID, const ASTContext &C,
633 ID.AddInteger(Parm->getDepth());
634 ID.AddInteger(Parm->getPosition());
635 ID.AddBoolean(Parm->isParameterPack());
636 ID.AddInteger(Parm->templateParameterKind());
637
639 ID.AddInteger(Params->size());
641 PEnd = Params->end();
642 P != PEnd; ++P) {
643 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
644 ID.AddInteger(0);
645 ID.AddBoolean(TTP->isParameterPack());
646 ID.AddInteger(
647 TTP->getNumExpansionParameters().toInternalRepresentation());
648 continue;
649 }
650
651 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
652 ID.AddInteger(1);
653 ID.AddBoolean(NTTP->isParameterPack());
654 ID.AddPointer(C.getUnconstrainedType(C.getCanonicalType(NTTP->getType()))
655 .getAsOpaquePtr());
656 if (NTTP->isExpandedParameterPack()) {
657 ID.AddBoolean(true);
658 ID.AddInteger(NTTP->getNumExpansionTypes());
659 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
660 QualType T = NTTP->getExpansionType(I);
661 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
662 }
663 } else
664 ID.AddBoolean(false);
665 continue;
666 }
667
668 auto *TTP = cast<TemplateTemplateParmDecl>(*P);
669 ID.AddInteger(2);
670 Profile(ID, C, TTP);
671 }
672}
673
674TemplateTemplateParmDecl *
676 TemplateTemplateParmDecl *TTP) const {
677 // Check if we already have a canonical template template parameter.
678 llvm::FoldingSetNodeID ID;
679 CanonicalTemplateTemplateParm::Profile(ID, *this, TTP);
680 void *InsertPos = nullptr;
681 CanonicalTemplateTemplateParm *Canonical
682 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
683 if (Canonical)
684 return Canonical->getParam();
685
686 // Build a canonical template parameter list.
688 SmallVector<NamedDecl *, 4> CanonParams;
689 CanonParams.reserve(Params->size());
691 PEnd = Params->end();
692 P != PEnd; ++P) {
693 // Note that, per C++20 [temp.over.link]/6, when determining whether
694 // template-parameters are equivalent, constraints are ignored.
695 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
698 TTP->getDepth(), TTP->getIndex(), nullptr, false,
699 TTP->isParameterPack(), /*HasTypeConstraint=*/false,
700 TTP->getNumExpansionParameters());
701 CanonParams.push_back(NewTTP);
702 } else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
703 QualType T = getUnconstrainedType(getCanonicalType(NTTP->getType()));
706 if (NTTP->isExpandedParameterPack()) {
707 SmallVector<QualType, 2> ExpandedTypes;
709 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
710 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
711 ExpandedTInfos.push_back(
712 getTrivialTypeSourceInfo(ExpandedTypes.back()));
713 }
714
718 NTTP->getDepth(),
719 NTTP->getPosition(), nullptr,
720 T,
721 TInfo,
722 ExpandedTypes,
723 ExpandedTInfos);
724 } else {
728 NTTP->getDepth(),
729 NTTP->getPosition(), nullptr,
730 T,
731 NTTP->isParameterPack(),
732 TInfo);
733 }
734 CanonParams.push_back(Param);
735 } else
736 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
738 }
739
742 TTP->getPosition(), TTP->isParameterPack(), nullptr,
744 /*Typename=*/false,
746 CanonParams, SourceLocation(),
747 /*RequiresClause=*/nullptr));
748
749 // Get the new insert position for the node we care about.
750 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
751 assert(!Canonical && "Shouldn't be in the map!");
752 (void)Canonical;
753
754 // Create the canonical template template parameter entry.
755 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
756 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
757 return CanonTTP;
758}
759
762 TemplateTemplateParmDecl *TTP) const {
763 llvm::FoldingSetNodeID ID;
764 CanonicalTemplateTemplateParm::Profile(ID, *this, TTP);
765 void *InsertPos = nullptr;
766 CanonicalTemplateTemplateParm *Canonical =
767 CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
768 return Canonical ? Canonical->getParam() : nullptr;
769}
770
773 TemplateTemplateParmDecl *CanonTTP) const {
774 llvm::FoldingSetNodeID ID;
775 CanonicalTemplateTemplateParm::Profile(ID, *this, CanonTTP);
776 void *InsertPos = nullptr;
777 if (auto *Existing =
778 CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos))
779 return Existing->getParam();
780 CanonTemplateTemplateParms.InsertNode(
781 new (*this) CanonicalTemplateTemplateParm(CanonTTP), InsertPos);
782 return CanonTTP;
783}
784
785/// For the purposes of overflow pattern exclusion, does this match the
786/// while(i--) pattern?
787static bool matchesPostDecrInWhile(const UnaryOperator *UO, ASTContext &Ctx) {
788 if (UO->getOpcode() != UO_PostDec)
789 return false;
790
791 if (!UO->getType()->isUnsignedIntegerType())
792 return false;
793
794 // -fsanitize-undefined-ignore-overflow-pattern=unsigned-post-decr-while
797 return false;
798
799 // all Parents (usually just one) must be a WhileStmt
800 return llvm::all_of(
802 [](const DynTypedNode &P) { return P.get<WhileStmt>() != nullptr; });
803}
804
806 // -fsanitize-undefined-ignore-overflow-pattern=negated-unsigned-const
807 // ... like -1UL;
808 if (UO->getOpcode() == UO_Minus &&
809 getLangOpts().isOverflowPatternExcluded(
811 UO->isIntegerConstantExpr(*this)) {
812 return true;
813 }
814
815 if (matchesPostDecrInWhile(UO, *this))
816 return true;
817
818 return false;
819}
820
821/// Check if a type can have its sanitizer instrumentation elided based on its
822/// presence within an ignorelist.
824 const QualType &Ty) const {
825 std::string TyName = Ty.getUnqualifiedType().getAsString(getPrintingPolicy());
826 return NoSanitizeL->containsType(Mask, TyName);
827}
828
830 auto Kind = getTargetInfo().getCXXABI().getKind();
831 return getLangOpts().CXXABI.value_or(Kind);
832}
833
834CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
835 if (!LangOpts.CPlusPlus) return nullptr;
836
837 switch (getCXXABIKind()) {
838 case TargetCXXABI::AppleARM64:
839 case TargetCXXABI::Fuchsia:
840 case TargetCXXABI::GenericARM: // Same as Itanium at this level
841 case TargetCXXABI::iOS:
842 case TargetCXXABI::WatchOS:
843 case TargetCXXABI::GenericAArch64:
844 case TargetCXXABI::GenericMIPS:
845 case TargetCXXABI::GenericItanium:
846 case TargetCXXABI::WebAssembly:
847 case TargetCXXABI::XL:
848 return CreateItaniumCXXABI(*this);
849 case TargetCXXABI::Microsoft:
850 return CreateMicrosoftCXXABI(*this);
851 }
852 llvm_unreachable("Invalid CXXABI type!");
853}
854
856 if (!InterpContext) {
857 InterpContext.reset(new interp::Context(const_cast<ASTContext &>(*this)));
858 }
859 return *InterpContext;
860}
861
863 if (!ParentMapCtx)
864 ParentMapCtx.reset(new ParentMapContext(*this));
865 return *ParentMapCtx;
866}
867
869 const LangOptions &LangOpts) {
870 switch (LangOpts.getAddressSpaceMapMangling()) {
872 return TI.useAddressSpaceMapMangling();
874 return true;
876 return false;
877 }
878 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
879}
880
882 IdentifierTable &idents, SelectorTable &sels,
884 : ConstantArrayTypes(this_(), ConstantArrayTypesLog2InitSize),
885 DependentSizedArrayTypes(this_()), DependentSizedExtVectorTypes(this_()),
886 DependentAddressSpaceTypes(this_()), DependentVectorTypes(this_()),
887 DependentSizedMatrixTypes(this_()),
888 FunctionProtoTypes(this_(), FunctionProtoTypesLog2InitSize),
889 DependentTypeOfExprTypes(this_()), DependentDecltypeTypes(this_()),
890 DependentPackIndexingTypes(this_()), TemplateSpecializationTypes(this_()),
891 DependentBitIntTypes(this_()), SubstTemplateTemplateParmPacks(this_()),
892 DeducedTemplates(this_()), ArrayParameterTypes(this_()),
893 CanonTemplateTemplateParms(this_()), SourceMgr(SM), LangOpts(LOpts),
894 NoSanitizeL(new NoSanitizeList(LangOpts.NoSanitizeFiles, SM)),
895 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
896 LangOpts.XRayNeverInstrumentFiles,
897 LangOpts.XRayAttrListFiles, SM)),
898 ProfList(new ProfileList(LangOpts.ProfileListFiles, SM)),
899 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
900 BuiltinInfo(builtins), TUKind(TUKind), DeclarationNames(*this),
901 Comments(SM), CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
902 CompCategories(this_()), LastSDM(nullptr, 0) {
904}
905
907 // Release the DenseMaps associated with DeclContext objects.
908 // FIXME: Is this the ideal solution?
909 ReleaseDeclContextMaps();
910
911 // Call all of the deallocation functions on all of their targets.
912 for (auto &Pair : Deallocations)
913 (Pair.first)(Pair.second);
914 Deallocations.clear();
915
916 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
917 // because they can contain DenseMaps.
918 for (llvm::DenseMap<const ObjCInterfaceDecl *,
920 I = ObjCLayouts.begin(),
921 E = ObjCLayouts.end();
922 I != E;)
923 // Increment in loop to prevent using deallocated memory.
924 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
925 R->Destroy(*this);
926 ObjCLayouts.clear();
927
928 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
929 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
930 // Increment in loop to prevent using deallocated memory.
931 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
932 R->Destroy(*this);
933 }
934 ASTRecordLayouts.clear();
935
936 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
937 AEnd = DeclAttrs.end();
938 A != AEnd; ++A)
939 A->second->~AttrVec();
940 DeclAttrs.clear();
941
942 for (const auto &Value : ModuleInitializers)
943 Value.second->~PerModuleInitializers();
944 ModuleInitializers.clear();
945
946 TUDecl = nullptr;
947 XRayFilter.reset();
948 NoSanitizeL.reset();
949}
950
952
953void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
954 TraversalScope = TopLevelDecls;
956}
957
958void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const {
959 Deallocations.push_back({Callback, Data});
960}
961
962void
966
968 llvm::errs() << "\n*** AST Context Stats:\n";
969 llvm::errs() << " " << Types.size() << " types total.\n";
970
971 unsigned counts[] = {
972#define TYPE(Name, Parent) 0,
973#define ABSTRACT_TYPE(Name, Parent)
974#include "clang/AST/TypeNodes.inc"
975 0 // Extra
976 };
977
978 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
979 Type *T = Types[i];
980 counts[(unsigned)T->getTypeClass()]++;
981 }
982
983 unsigned Idx = 0;
984 unsigned TotalBytes = 0;
985#define TYPE(Name, Parent) \
986 if (counts[Idx]) \
987 llvm::errs() << " " << counts[Idx] << " " << #Name \
988 << " types, " << sizeof(Name##Type) << " each " \
989 << "(" << counts[Idx] * sizeof(Name##Type) \
990 << " bytes)\n"; \
991 TotalBytes += counts[Idx] * sizeof(Name##Type); \
992 ++Idx;
993#define ABSTRACT_TYPE(Name, Parent)
994#include "clang/AST/TypeNodes.inc"
995
996 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
997
998 // Implicit special member functions.
999 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
1001 << " implicit default constructors created\n";
1002 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
1004 << " implicit copy constructors created\n";
1005 if (getLangOpts().CPlusPlus)
1006 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
1008 << " implicit move constructors created\n";
1009 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
1011 << " implicit copy assignment operators created\n";
1012 if (getLangOpts().CPlusPlus)
1013 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
1015 << " implicit move assignment operators created\n";
1016 llvm::errs() << NumImplicitDestructorsDeclared << "/"
1018 << " implicit destructors created\n";
1019
1020 if (ExternalSource) {
1021 llvm::errs() << "\n";
1022 ExternalSource->PrintStats();
1023 }
1024
1025 BumpAlloc.PrintStats();
1026}
1027
1029 bool NotifyListeners) {
1030 if (NotifyListeners)
1031 if (auto *Listener = getASTMutationListener();
1033 Listener->RedefinedHiddenDefinition(ND, M);
1034
1035 MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M);
1036}
1037
1039 auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl()));
1040 if (It == MergedDefModules.end())
1041 return;
1042
1043 auto &Merged = It->second;
1044 llvm::DenseSet<Module*> Found;
1045 for (Module *&M : Merged)
1046 if (!Found.insert(M).second)
1047 M = nullptr;
1048 llvm::erase(Merged, nullptr);
1049}
1050
1053 auto MergedIt =
1054 MergedDefModules.find(cast<NamedDecl>(Def->getCanonicalDecl()));
1055 if (MergedIt == MergedDefModules.end())
1056 return {};
1057 return MergedIt->second;
1058}
1059
1060void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
1061 if (LazyInitializers.empty())
1062 return;
1063
1064 auto *Source = Ctx.getExternalSource();
1065 assert(Source && "lazy initializers but no external source");
1066
1067 auto LazyInits = std::move(LazyInitializers);
1068 LazyInitializers.clear();
1069
1070 for (auto ID : LazyInits)
1071 Initializers.push_back(Source->GetExternalDecl(ID));
1072
1073 assert(LazyInitializers.empty() &&
1074 "GetExternalDecl for lazy module initializer added more inits");
1075}
1076
1078 // One special case: if we add a module initializer that imports another
1079 // module, and that module's only initializer is an ImportDecl, simplify.
1080 if (const auto *ID = dyn_cast<ImportDecl>(D)) {
1081 auto It = ModuleInitializers.find(ID->getImportedModule());
1082
1083 // Maybe the ImportDecl does nothing at all. (Common case.)
1084 if (It == ModuleInitializers.end())
1085 return;
1086
1087 // Maybe the ImportDecl only imports another ImportDecl.
1088 auto &Imported = *It->second;
1089 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
1090 Imported.resolve(*this);
1091 auto *OnlyDecl = Imported.Initializers.front();
1092 if (isa<ImportDecl>(OnlyDecl))
1093 D = OnlyDecl;
1094 }
1095 }
1096
1097 auto *&Inits = ModuleInitializers[M];
1098 if (!Inits)
1099 Inits = new (*this) PerModuleInitializers;
1100 Inits->Initializers.push_back(D);
1101}
1102
1105 auto *&Inits = ModuleInitializers[M];
1106 if (!Inits)
1107 Inits = new (*this) PerModuleInitializers;
1108 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
1109 IDs.begin(), IDs.end());
1110}
1111
1113 auto It = ModuleInitializers.find(M);
1114 if (It == ModuleInitializers.end())
1115 return {};
1116
1117 auto *Inits = It->second;
1118 Inits->resolve(*this);
1119 return Inits->Initializers;
1120}
1121
1123 assert(M->isNamedModule());
1124 assert(!CurrentCXXNamedModule &&
1125 "We should set named module for ASTContext for only once");
1126 CurrentCXXNamedModule = M;
1127}
1128
1129bool ASTContext::isInSameModule(const Module *M1, const Module *M2) const {
1130 if (!M1 != !M2)
1131 return false;
1132
1133 /// Get the representative module for M. The representative module is the
1134 /// first module unit for a specific primary module name. So that the module
1135 /// units have the same representative module belongs to the same module.
1136 ///
1137 /// The process is helpful to reduce the expensive string operations.
1138 auto GetRepresentativeModule = [this](const Module *M) {
1139 auto Iter = SameModuleLookupSet.find(M);
1140 if (Iter != SameModuleLookupSet.end())
1141 return Iter->second;
1142
1143 const Module *RepresentativeModule =
1144 PrimaryModuleNameMap.try_emplace(M->getPrimaryModuleInterfaceName(), M)
1145 .first->second;
1146 SameModuleLookupSet[M] = RepresentativeModule;
1147 return RepresentativeModule;
1148 };
1149
1150 assert(M1 && "Shouldn't call `isInSameModule` if both M1 and M2 are none.");
1151 return GetRepresentativeModule(M1) == GetRepresentativeModule(M2);
1152}
1153
1155 if (!ExternCContext)
1156 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1157
1158 return ExternCContext;
1159}
1160
1171
1172#define BuiltinTemplate(BTName) \
1173 BuiltinTemplateDecl *ASTContext::get##BTName##Decl() const { \
1174 if (!Decl##BTName) \
1175 Decl##BTName = \
1176 buildBuiltinTemplateDecl(BTK##BTName, get##BTName##Name()); \
1177 return Decl##BTName; \
1178 }
1179#include "clang/Basic/BuiltinTemplates.inc"
1180
1182 RecordDecl::TagKind TK) const {
1183 SourceLocation Loc;
1184 RecordDecl *NewDecl;
1185 if (getLangOpts().CPlusPlus)
1186 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1187 Loc, &Idents.get(Name));
1188 else
1189 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1190 &Idents.get(Name));
1191 NewDecl->setImplicit();
1192 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1193 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
1194 return NewDecl;
1195}
1196
1198 StringRef Name) const {
1201 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1202 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1203 NewDecl->setImplicit();
1204 return NewDecl;
1205}
1206
1208 if (!Int128Decl)
1209 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
1210 return Int128Decl;
1211}
1212
1214 if (!UInt128Decl)
1215 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
1216 return UInt128Decl;
1217}
1218
1219void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
1220 auto *Ty = new (*this, alignof(BuiltinType)) BuiltinType(K);
1222 Types.push_back(Ty);
1223}
1224
1226 const TargetInfo *AuxTarget) {
1227 assert((!this->Target || this->Target == &Target) &&
1228 "Incorrect target reinitialization");
1229 assert(VoidTy.isNull() && "Context reinitialized?");
1230
1231 this->Target = &Target;
1232 this->AuxTarget = AuxTarget;
1233
1234 ABI.reset(createCXXABI(Target));
1235 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
1236
1237 // C99 6.2.5p19.
1238 InitBuiltinType(VoidTy, BuiltinType::Void);
1239
1240 // C99 6.2.5p2.
1241 InitBuiltinType(BoolTy, BuiltinType::Bool);
1242 // C99 6.2.5p3.
1243 if (LangOpts.CharIsSigned)
1244 InitBuiltinType(CharTy, BuiltinType::Char_S);
1245 else
1246 InitBuiltinType(CharTy, BuiltinType::Char_U);
1247 // C99 6.2.5p4.
1248 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1249 InitBuiltinType(ShortTy, BuiltinType::Short);
1250 InitBuiltinType(IntTy, BuiltinType::Int);
1251 InitBuiltinType(LongTy, BuiltinType::Long);
1252 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
1253
1254 // C99 6.2.5p6.
1255 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1256 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1257 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1258 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1259 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
1260
1261 // C99 6.2.5p10.
1262 InitBuiltinType(FloatTy, BuiltinType::Float);
1263 InitBuiltinType(DoubleTy, BuiltinType::Double);
1264 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
1265
1266 // GNU extension, __float128 for IEEE quadruple precision
1267 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1268
1269 // __ibm128 for IBM extended precision
1270 InitBuiltinType(Ibm128Ty, BuiltinType::Ibm128);
1271
1272 // C11 extension ISO/IEC TS 18661-3
1273 InitBuiltinType(Float16Ty, BuiltinType::Float16);
1274
1275 // ISO/IEC JTC1 SC22 WG14 N1169 Extension
1276 InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum);
1277 InitBuiltinType(AccumTy, BuiltinType::Accum);
1278 InitBuiltinType(LongAccumTy, BuiltinType::LongAccum);
1279 InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum);
1280 InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum);
1281 InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum);
1282 InitBuiltinType(ShortFractTy, BuiltinType::ShortFract);
1283 InitBuiltinType(FractTy, BuiltinType::Fract);
1284 InitBuiltinType(LongFractTy, BuiltinType::LongFract);
1285 InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract);
1286 InitBuiltinType(UnsignedFractTy, BuiltinType::UFract);
1287 InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract);
1288 InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum);
1289 InitBuiltinType(SatAccumTy, BuiltinType::SatAccum);
1290 InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum);
1291 InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
1292 InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum);
1293 InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum);
1294 InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract);
1295 InitBuiltinType(SatFractTy, BuiltinType::SatFract);
1296 InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract);
1297 InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
1298 InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract);
1299 InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract);
1300
1301 // GNU extension, 128-bit integers.
1302 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1303 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1304
1305 // C++ 3.9.1p5
1306 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1307 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1308 else // -fshort-wchar makes wchar_t be unsigned.
1309 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1310 if (LangOpts.CPlusPlus && LangOpts.WChar)
1312 else {
1313 // C99 (or C++ using -fno-wchar).
1314 WideCharTy = getFromTargetType(Target.getWCharType());
1315 }
1316
1317 WIntTy = getFromTargetType(Target.getWIntType());
1318
1319 // C++20 (proposed)
1320 InitBuiltinType(Char8Ty, BuiltinType::Char8);
1321
1322 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1323 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1324 else // C99
1325 Char16Ty = getFromTargetType(Target.getChar16Type());
1326
1327 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1328 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1329 else // C99
1330 Char32Ty = getFromTargetType(Target.getChar32Type());
1331
1332 // Placeholder type for type-dependent expressions whose type is
1333 // completely unknown. No code should ever check a type against
1334 // DependentTy and users should never see it; however, it is here to
1335 // help diagnose failures to properly check for type-dependent
1336 // expressions.
1337 InitBuiltinType(DependentTy, BuiltinType::Dependent);
1338
1339 // Placeholder type for functions.
1340 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1341
1342 // Placeholder type for bound members.
1343 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1344
1345 // Placeholder type for unresolved templates.
1346 InitBuiltinType(UnresolvedTemplateTy, BuiltinType::UnresolvedTemplate);
1347
1348 // Placeholder type for pseudo-objects.
1349 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1350
1351 // "any" type; useful for debugger-like clients.
1352 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1353
1354 // Placeholder type for unbridged ARC casts.
1355 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1356
1357 // Placeholder type for builtin functions.
1358 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1359
1360 // Placeholder type for OMP array sections.
1361 if (LangOpts.OpenMP) {
1362 InitBuiltinType(ArraySectionTy, BuiltinType::ArraySection);
1363 InitBuiltinType(OMPArrayShapingTy, BuiltinType::OMPArrayShaping);
1364 InitBuiltinType(OMPIteratorTy, BuiltinType::OMPIterator);
1365 }
1366 // Placeholder type for OpenACC array sections, if we are ALSO in OMP mode,
1367 // don't bother, as we're just using the same type as OMP.
1368 if (LangOpts.OpenACC && !LangOpts.OpenMP) {
1369 InitBuiltinType(ArraySectionTy, BuiltinType::ArraySection);
1370 }
1371 if (LangOpts.MatrixTypes)
1372 InitBuiltinType(IncompleteMatrixIdxTy, BuiltinType::IncompleteMatrixIdx);
1373
1374 // Builtin types for 'id', 'Class', and 'SEL'.
1375 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1376 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
1377 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
1378
1379 if (LangOpts.OpenCL) {
1380#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1381 InitBuiltinType(SingletonId, BuiltinType::Id);
1382#include "clang/Basic/OpenCLImageTypes.def"
1383
1384 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
1385 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
1386 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1387 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1388 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
1389
1390#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1391 InitBuiltinType(Id##Ty, BuiltinType::Id);
1392#include "clang/Basic/OpenCLExtensionTypes.def"
1393 }
1394
1395 if (LangOpts.HLSL) {
1396#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
1397 InitBuiltinType(SingletonId, BuiltinType::Id);
1398#include "clang/Basic/HLSLIntangibleTypes.def"
1399 }
1400
1401 if (Target.hasAArch64ACLETypes() ||
1402 (AuxTarget && AuxTarget->hasAArch64ACLETypes())) {
1403#define SVE_TYPE(Name, Id, SingletonId) \
1404 InitBuiltinType(SingletonId, BuiltinType::Id);
1405#include "clang/Basic/AArch64ACLETypes.def"
1406 }
1407
1408 if (Target.getTriple().isPPC64()) {
1409#define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
1410 InitBuiltinType(Id##Ty, BuiltinType::Id);
1411#include "clang/Basic/PPCTypes.def"
1412#define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
1413 InitBuiltinType(Id##Ty, BuiltinType::Id);
1414#include "clang/Basic/PPCTypes.def"
1415 }
1416
1417 if (Target.hasRISCVVTypes()) {
1418#define RVV_TYPE(Name, Id, SingletonId) \
1419 InitBuiltinType(SingletonId, BuiltinType::Id);
1420#include "clang/Basic/RISCVVTypes.def"
1421 }
1422
1423 if (Target.getTriple().isWasm() && Target.hasFeature("reference-types")) {
1424#define WASM_TYPE(Name, Id, SingletonId) \
1425 InitBuiltinType(SingletonId, BuiltinType::Id);
1426#include "clang/Basic/WebAssemblyReferenceTypes.def"
1427 }
1428
1429 if (Target.getTriple().isAMDGPU() ||
1430 (Target.getTriple().isSPIRV() &&
1431 Target.getTriple().getVendor() == llvm::Triple::AMD) ||
1432 (AuxTarget &&
1433 (AuxTarget->getTriple().isAMDGPU() ||
1434 ((AuxTarget->getTriple().isSPIRV() &&
1435 AuxTarget->getTriple().getVendor() == llvm::Triple::AMD))))) {
1436#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) \
1437 InitBuiltinType(SingletonId, BuiltinType::Id);
1438#include "clang/Basic/AMDGPUTypes.def"
1439 }
1440
1441 // Builtin type for __objc_yes and __objc_no
1442 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1444
1445 ObjCConstantStringType = QualType();
1446
1447 ObjCSuperType = QualType();
1448
1449 // void * type
1450 if (LangOpts.OpenCLGenericAddressSpace) {
1451 auto Q = VoidTy.getQualifiers();
1452 Q.setAddressSpace(LangAS::opencl_generic);
1454 getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
1455 } else {
1457 }
1458
1459 // nullptr type (C++0x 2.14.7)
1460 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
1461
1462 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1463 InitBuiltinType(HalfTy, BuiltinType::Half);
1464
1465 InitBuiltinType(BFloat16Ty, BuiltinType::BFloat16);
1466
1467 // Builtin type used to help define __builtin_va_list.
1468 VaListTagDecl = nullptr;
1469
1470 // MSVC predeclares struct _GUID, and we need it to create MSGuidDecls.
1471 if (LangOpts.MicrosoftExt || LangOpts.Borland) {
1474 }
1475}
1476
1478 return SourceMgr.getDiagnostics();
1479}
1480
1482 AttrVec *&Result = DeclAttrs[D];
1483 if (!Result) {
1484 void *Mem = Allocate(sizeof(AttrVec));
1485 Result = new (Mem) AttrVec;
1486 }
1487
1488 return *Result;
1489}
1490
1491/// Erase the attributes corresponding to the given declaration.
1493 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1494 if (Pos != DeclAttrs.end()) {
1495 Pos->second->~AttrVec();
1496 DeclAttrs.erase(Pos);
1497 }
1498}
1499
1502 auto It =
1503 ExplicitInstantiations.find(cast<NamedDecl>(Spec->getCanonicalDecl()));
1504 if (It != ExplicitInstantiations.end())
1505 return It->second;
1506 return {};
1507}
1508
1511 ExplicitInstantiations[cast<NamedDecl>(Spec->getCanonicalDecl())].push_back(
1512 EID);
1513}
1514
1515// FIXME: Remove ?
1518 assert(Var->isStaticDataMember() && "Not a static data member");
1520 .dyn_cast<MemberSpecializationInfo *>();
1521}
1522
1525 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1526 TemplateOrInstantiation.find(Var);
1527 if (Pos == TemplateOrInstantiation.end())
1528 return {};
1529
1530 return Pos->second;
1531}
1532
1533void
1536 SourceLocation PointOfInstantiation) {
1537 assert(Inst->isStaticDataMember() && "Not a static data member");
1538 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1540 Tmpl, TSK, PointOfInstantiation));
1541}
1542
1543void
1546 assert(!TemplateOrInstantiation[Inst] &&
1547 "Already noted what the variable was instantiated from");
1548 TemplateOrInstantiation[Inst] = TSI;
1549}
1550
1551NamedDecl *
1553 return InstantiatedFromUsingDecl.lookup(UUD);
1554}
1555
1556void
1558 assert((isa<UsingDecl>(Pattern) ||
1561 "pattern decl is not a using decl");
1562 assert((isa<UsingDecl>(Inst) ||
1565 "instantiation did not produce a using decl");
1566 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1567 InstantiatedFromUsingDecl[Inst] = Pattern;
1568}
1569
1572 return InstantiatedFromUsingEnumDecl.lookup(UUD);
1573}
1574
1576 UsingEnumDecl *Pattern) {
1577 assert(!InstantiatedFromUsingEnumDecl[Inst] && "pattern already exists");
1578 InstantiatedFromUsingEnumDecl[Inst] = Pattern;
1579}
1580
1583 return InstantiatedFromUsingShadowDecl.lookup(Inst);
1584}
1585
1586void
1588 UsingShadowDecl *Pattern) {
1589 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1590 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1591}
1592
1593FieldDecl *
1595 return InstantiatedFromUnnamedFieldDecl.lookup(Field);
1596}
1597
1599 FieldDecl *Tmpl) {
1600 assert((!Inst->getDeclName() || Inst->isPlaceholderVar(getLangOpts())) &&
1601 "Instantiated field decl is not unnamed");
1602 assert((!Inst->getDeclName() || Inst->isPlaceholderVar(getLangOpts())) &&
1603 "Template field decl is not unnamed");
1604 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1605 "Already noted what unnamed field was instantiated from");
1606
1607 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1608}
1609
1614
1619
1620unsigned
1622 auto Range = overridden_methods(Method);
1623 return Range.end() - Range.begin();
1624}
1625
1628 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1629 OverriddenMethods.find(Method->getCanonicalDecl());
1630 if (Pos == OverriddenMethods.end())
1631 return overridden_method_range(nullptr, nullptr);
1632 return overridden_method_range(Pos->second.begin(), Pos->second.end());
1633}
1634
1636 const CXXMethodDecl *Overridden) {
1637 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1638 OverriddenMethods[Method].push_back(Overridden);
1639}
1640
1642 const NamedDecl *D,
1643 SmallVectorImpl<const NamedDecl *> &Overridden) const {
1644 assert(D);
1645
1646 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1647 Overridden.append(overridden_methods_begin(CXXMethod),
1648 overridden_methods_end(CXXMethod));
1649 return;
1650 }
1651
1652 const auto *Method = dyn_cast<ObjCMethodDecl>(D);
1653 if (!Method)
1654 return;
1655
1657 Method->getOverriddenMethods(OverDecls);
1658 Overridden.append(OverDecls.begin(), OverDecls.end());
1659}
1660
1661std::optional<ASTContext::CXXRecordDeclRelocationInfo>
1663 assert(RD);
1664 CXXRecordDecl *D = RD->getDefinition();
1665 auto it = RelocatableClasses.find(D);
1666 if (it != RelocatableClasses.end())
1667 return it->getSecond();
1668 return std::nullopt;
1669}
1670
1673 assert(RD);
1674 CXXRecordDecl *D = RD->getDefinition();
1675 assert(RelocatableClasses.find(D) == RelocatableClasses.end());
1676 RelocatableClasses.insert({D, Info});
1677}
1678
1680 const ASTContext &Context, const CXXRecordDecl *Class) {
1681 if (!Class->isPolymorphic())
1682 return false;
1683 const CXXRecordDecl *BaseType = Context.baseForVTableAuthentication(Class);
1684 using AuthAttr = VTablePointerAuthenticationAttr;
1685 const AuthAttr *ExplicitAuth = BaseType->getAttr<AuthAttr>();
1686 if (!ExplicitAuth)
1687 return Context.getLangOpts().PointerAuthVTPtrAddressDiscrimination;
1688 AuthAttr::AddressDiscriminationMode AddressDiscrimination =
1689 ExplicitAuth->getAddressDiscrimination();
1690 if (AddressDiscrimination == AuthAttr::DefaultAddressDiscrimination)
1691 return Context.getLangOpts().PointerAuthVTPtrAddressDiscrimination;
1692 return AddressDiscrimination == AuthAttr::AddressDiscrimination;
1693}
1694
1695ASTContext::PointerAuthContent
1696ASTContext::findPointerAuthContent(QualType T) const {
1697 assert(isPointerAuthenticationAvailable());
1698
1699 T = T.getCanonicalType();
1700 if (T->isDependentType())
1701 return PointerAuthContent::None;
1702
1704 return PointerAuthContent::AddressDiscriminatedData;
1705 const RecordDecl *RD = T->getAsRecordDecl();
1706 if (!RD)
1707 return PointerAuthContent::None;
1708
1709 if (RD->isInvalidDecl())
1710 return PointerAuthContent::None;
1711
1712 if (auto Existing = RecordContainsAddressDiscriminatedPointerAuth.find(RD);
1713 Existing != RecordContainsAddressDiscriminatedPointerAuth.end())
1714 return Existing->second;
1715
1716 PointerAuthContent Result = PointerAuthContent::None;
1717
1718 auto SaveResultAndReturn = [&]() -> PointerAuthContent {
1719 auto [ResultIter, DidAdd] =
1720 RecordContainsAddressDiscriminatedPointerAuth.try_emplace(RD, Result);
1721 (void)ResultIter;
1722 (void)DidAdd;
1723 assert(DidAdd);
1724 return Result;
1725 };
1726 auto ShouldContinueAfterUpdate = [&](PointerAuthContent NewResult) {
1727 static_assert(PointerAuthContent::None <
1728 PointerAuthContent::AddressDiscriminatedVTable);
1729 static_assert(PointerAuthContent::AddressDiscriminatedVTable <
1730 PointerAuthContent::AddressDiscriminatedData);
1731 if (NewResult > Result)
1732 Result = NewResult;
1733 return Result != PointerAuthContent::AddressDiscriminatedData;
1734 };
1735 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1737 !ShouldContinueAfterUpdate(
1738 PointerAuthContent::AddressDiscriminatedVTable))
1739 return SaveResultAndReturn();
1740 for (auto Base : CXXRD->bases()) {
1741 if (!ShouldContinueAfterUpdate(findPointerAuthContent(Base.getType())))
1742 return SaveResultAndReturn();
1743 }
1744 }
1745 for (auto *FieldDecl : RD->fields()) {
1746 if (!ShouldContinueAfterUpdate(
1747 findPointerAuthContent(FieldDecl->getType())))
1748 return SaveResultAndReturn();
1749 }
1750 return SaveResultAndReturn();
1751}
1752
1754 assert(!Import->getNextLocalImport() &&
1755 "Import declaration already in the chain");
1756 assert(!Import->isFromASTFile() && "Non-local import declaration");
1757 if (!FirstLocalImport) {
1758 FirstLocalImport = Import;
1759 LastLocalImport = Import;
1760 return;
1761 }
1762
1763 LastLocalImport->setNextLocalImport(Import);
1764 LastLocalImport = Import;
1765}
1766
1767//===----------------------------------------------------------------------===//
1768// Type Sizing and Analysis
1769//===----------------------------------------------------------------------===//
1770
1771/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1772/// scalar floating point type.
1773const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1774 switch (T->castAs<BuiltinType>()->getKind()) {
1775 default:
1776 llvm_unreachable("Not a floating point type!");
1777 case BuiltinType::BFloat16:
1778 return Target->getBFloat16Format();
1779 case BuiltinType::Float16:
1780 return Target->getHalfFormat();
1781 case BuiltinType::Half:
1782 return Target->getHalfFormat();
1783 case BuiltinType::Float: return Target->getFloatFormat();
1784 case BuiltinType::Double: return Target->getDoubleFormat();
1785 case BuiltinType::Ibm128:
1786 return Target->getIbm128Format();
1787 case BuiltinType::LongDouble:
1788 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1789 return AuxTarget->getLongDoubleFormat();
1790 return Target->getLongDoubleFormat();
1791 case BuiltinType::Float128:
1792 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1793 return AuxTarget->getFloat128Format();
1794 return Target->getFloat128Format();
1795 }
1796}
1797
1798CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1799 unsigned Align = Target->getCharWidth();
1800
1801 const unsigned AlignFromAttr = D->getMaxAlignment();
1802 if (AlignFromAttr)
1803 Align = AlignFromAttr;
1804
1805 // __attribute__((aligned)) can increase or decrease alignment
1806 // *except* on a struct or struct member, where it only increases
1807 // alignment unless 'packed' is also specified.
1808 //
1809 // It is an error for alignas to decrease alignment, so we can
1810 // ignore that possibility; Sema should diagnose it.
1811 bool UseAlignAttrOnly;
1812 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D))
1813 UseAlignAttrOnly =
1814 FD->hasAttr<PackedAttr>() || FD->getParent()->hasAttr<PackedAttr>();
1815 else
1816 UseAlignAttrOnly = AlignFromAttr != 0;
1817 // If we're using the align attribute only, just ignore everything
1818 // else about the declaration and its type.
1819 if (UseAlignAttrOnly) {
1820 // do nothing
1821 } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
1822 QualType T = VD->getType();
1823 if (const auto *RT = T->getAs<ReferenceType>()) {
1824 if (ForAlignof)
1825 T = RT->getPointeeType();
1826 else
1827 T = getPointerType(RT->getPointeeType());
1828 }
1829 QualType BaseT = getBaseElementType(T);
1830 if (T->isFunctionType())
1831 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1832 else if (!BaseT->isIncompleteType()) {
1833 // Adjust alignments of declarations with array type by the
1834 // large-array alignment on the target.
1835 if (const ArrayType *arrayType = getAsArrayType(T)) {
1836 unsigned MinWidth = Target->getLargeArrayMinWidth();
1837 if (!ForAlignof && MinWidth) {
1839 Align = std::max(Align, Target->getLargeArrayAlign());
1842 Align = std::max(Align, Target->getLargeArrayAlign());
1843 }
1844 }
1845 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1846 if (BaseT.getQualifiers().hasUnaligned())
1847 Align = Target->getCharWidth();
1848 }
1849
1850 // Ensure minimum alignment for global variables.
1851 if (const auto *VD = dyn_cast<VarDecl>(D))
1852 if (VD->hasGlobalStorage() && !ForAlignof) {
1853 uint64_t TypeSize =
1854 !BaseT->isIncompleteType() ? getTypeSize(T.getTypePtr()) : 0;
1855 Align = std::max(Align, getMinGlobalAlignOfVar(TypeSize, VD));
1856 }
1857
1858 // Fields can be subject to extra alignment constraints, like if
1859 // the field is packed, the struct is packed, or the struct has a
1860 // a max-field-alignment constraint (#pragma pack). So calculate
1861 // the actual alignment of the field within the struct, and then
1862 // (as we're expected to) constrain that by the alignment of the type.
1863 if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
1864 const RecordDecl *Parent = Field->getParent();
1865 // We can only produce a sensible answer if the record is valid.
1866 if (!Parent->isInvalidDecl()) {
1867 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
1868
1869 // Start with the record's overall alignment.
1870 unsigned FieldAlign = toBits(Layout.getAlignment());
1871
1872 // Use the GCD of that and the offset within the record.
1873 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1874 if (Offset > 0) {
1875 // Alignment is always a power of 2, so the GCD will be a power of 2,
1876 // which means we get to do this crazy thing instead of Euclid's.
1877 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1878 if (LowBitOfOffset < FieldAlign)
1879 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1880 }
1881
1882 Align = std::min(Align, FieldAlign);
1883 }
1884 }
1885 }
1886
1887 // Some targets have hard limitation on the maximum requestable alignment in
1888 // aligned attribute for static variables.
1889 const unsigned MaxAlignedAttr = getTargetInfo().getMaxAlignedAttribute();
1890 const auto *VD = dyn_cast<VarDecl>(D);
1891 if (MaxAlignedAttr && VD && VD->getStorageClass() == SC_Static)
1892 Align = std::min(Align, MaxAlignedAttr);
1893
1894 return toCharUnitsFromBits(Align);
1895}
1896
1898 return toCharUnitsFromBits(Target->getExnObjectAlignment());
1899}
1900
1901// getTypeInfoDataSizeInChars - Return the size of a type, in
1902// chars. If the type is a record, its data size is returned. This is
1903// the size of the memcpy that's performed when assigning this type
1904// using a trivial copy/move assignment operator.
1907
1908 // In C++, objects can sometimes be allocated into the tail padding
1909 // of a base-class subobject. We decide whether that's possible
1910 // during class layout, so here we can just trust the layout results.
1911 if (getLangOpts().CPlusPlus) {
1912 if (const auto *RD = T->getAsCXXRecordDecl(); RD && !RD->isInvalidDecl()) {
1913 const ASTRecordLayout &layout = getASTRecordLayout(RD);
1914 Info.Width = layout.getDataSize();
1915 }
1916 }
1917
1918 return Info;
1919}
1920
1921/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1922/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1925 const ConstantArrayType *CAT) {
1926 TypeInfoChars EltInfo = Context.getTypeInfoInChars(CAT->getElementType());
1927 uint64_t Size = CAT->getZExtSize();
1928 assert((Size == 0 || static_cast<uint64_t>(EltInfo.Width.getQuantity()) <=
1929 (uint64_t)(-1)/Size) &&
1930 "Overflow in array type char size evaluation");
1931 uint64_t Width = EltInfo.Width.getQuantity() * Size;
1932 unsigned Align = EltInfo.Align.getQuantity();
1933 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1934 Context.getTargetInfo().getPointerWidth(LangAS::Default) == 64)
1935 Width = llvm::alignTo(Width, Align);
1938 EltInfo.AlignRequirement);
1939}
1940
1942 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
1943 return getConstantArrayInfoInChars(*this, CAT);
1944 TypeInfo Info = getTypeInfo(T);
1947}
1948
1950 return getTypeInfoInChars(T.getTypePtr());
1951}
1952
1954 // HLSL doesn't promote all small integer types to int, it
1955 // just uses the rank-based promotion rules for all types.
1956 if (getLangOpts().HLSL)
1957 return false;
1958
1959 if (const auto *BT = T->getAs<BuiltinType>())
1960 switch (BT->getKind()) {
1961 case BuiltinType::Bool:
1962 case BuiltinType::Char_S:
1963 case BuiltinType::Char_U:
1964 case BuiltinType::SChar:
1965 case BuiltinType::UChar:
1966 case BuiltinType::Short:
1967 case BuiltinType::UShort:
1968 case BuiltinType::WChar_S:
1969 case BuiltinType::WChar_U:
1970 case BuiltinType::Char8:
1971 case BuiltinType::Char16:
1972 case BuiltinType::Char32:
1973 return true;
1974 default:
1975 return false;
1976 }
1977
1978 // Enumerated types are promotable to their compatible integer types
1979 // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
1980 if (const auto *ED = T->getAsEnumDecl()) {
1981 if (T->isDependentType() || ED->getPromotionType().isNull() ||
1982 ED->isScoped())
1983 return false;
1984
1985 return true;
1986 }
1987
1988 // OverflowBehaviorTypes are promotable if their underlying type is promotable
1989 if (const auto *OBT = T->getAs<OverflowBehaviorType>()) {
1990 return isPromotableIntegerType(OBT->getUnderlyingType());
1991 }
1992
1993 return false;
1994}
1995
1999
2001 return isAlignmentRequired(T.getTypePtr());
2002}
2003
2005 bool NeedsPreferredAlignment) const {
2006 // An alignment on a typedef overrides anything else.
2007 if (const auto *TT = T->getAs<TypedefType>())
2008 if (unsigned Align = TT->getDecl()->getMaxAlignment())
2009 return Align;
2010
2011 // If we have an (array of) complete type, we're done.
2012 T = getBaseElementType(T);
2013 if (!T->isIncompleteType())
2014 return NeedsPreferredAlignment ? getPreferredTypeAlign(T) : getTypeAlign(T);
2015
2016 // If we had an array type, its element type might be a typedef
2017 // type with an alignment attribute.
2018 if (const auto *TT = T->getAs<TypedefType>())
2019 if (unsigned Align = TT->getDecl()->getMaxAlignment())
2020 return Align;
2021
2022 // Otherwise, see if the declaration of the type had an attribute.
2023 if (const auto *TD = T->getAsTagDecl())
2024 return TD->getMaxAlignment();
2025
2026 return 0;
2027}
2028
2030 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
2031 if (I != MemoizedTypeInfo.end())
2032 return I->second;
2033
2034 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
2035 TypeInfo TI = getTypeInfoImpl(T);
2036 MemoizedTypeInfo[T] = TI;
2037 return TI;
2038}
2039
2040/// getTypeInfoImpl - Return the size of the specified type, in bits. This
2041/// method does not work on incomplete types.
2042///
2043/// FIXME: Pointers into different addr spaces could have different sizes and
2044/// alignment requirements: getPointerInfo should take an AddrSpace, this
2045/// should take a QualType, &c.
2046TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
2047 uint64_t Width = 0;
2048 unsigned Align = 8;
2051 switch (T->getTypeClass()) {
2052#define TYPE(Class, Base)
2053#define ABSTRACT_TYPE(Class, Base)
2054#define NON_CANONICAL_TYPE(Class, Base)
2055#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2056#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
2057 case Type::Class: \
2058 assert(!T->isDependentType() && "should not see dependent types here"); \
2059 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
2060#include "clang/AST/TypeNodes.inc"
2061 llvm_unreachable("Should not see dependent types");
2062
2063 case Type::FunctionNoProto:
2064 case Type::FunctionProto:
2065 // GCC extension: alignof(function) = 32 bits
2066 Width = 0;
2067 Align = 32;
2068 break;
2069
2070 case Type::IncompleteArray:
2071 case Type::VariableArray:
2072 case Type::ConstantArray:
2073 case Type::ArrayParameter: {
2074 // Model non-constant sized arrays as size zero, but track the alignment.
2075 uint64_t Size = 0;
2076 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
2077 Size = CAT->getZExtSize();
2078
2079 TypeInfo EltInfo = getTypeInfo(cast<ArrayType>(T)->getElementType());
2080 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
2081 "Overflow in array type bit size evaluation");
2082 Width = EltInfo.Width * Size;
2083 Align = EltInfo.Align;
2084 AlignRequirement = EltInfo.AlignRequirement;
2085 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
2086 getTargetInfo().getPointerWidth(LangAS::Default) == 64)
2087 Width = llvm::alignTo(Width, Align);
2088 break;
2089 }
2090
2091 case Type::ExtVector:
2092 case Type::Vector: {
2093 const auto *VT = cast<VectorType>(T);
2094 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
2095 Width = VT->isPackedVectorBoolType(*this)
2096 ? VT->getNumElements()
2097 : EltInfo.Width * VT->getNumElements();
2098 // Enforce at least byte size and alignment.
2099 Width = std::max<unsigned>(8, Width);
2100 Align = std::max<unsigned>(
2101 8, Target->vectorsAreElementAligned() ? EltInfo.Width : Width);
2102
2103 // If the alignment is not a power of 2, round up to the next power of 2.
2104 // This happens for non-power-of-2 length vectors.
2105 if (Align & (Align-1)) {
2106 Align = llvm::bit_ceil(Align);
2107 Width = llvm::alignTo(Width, Align);
2108 }
2109 // Adjust the alignment based on the target max.
2110 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
2111 if (TargetVectorAlign && TargetVectorAlign < Align)
2112 Align = TargetVectorAlign;
2113 if (VT->getVectorKind() == VectorKind::SveFixedLengthData)
2114 // Adjust the alignment for fixed-length SVE vectors. This is important
2115 // for non-power-of-2 vector lengths.
2116 Align = 128;
2117 else if (VT->getVectorKind() == VectorKind::SveFixedLengthPredicate)
2118 // Adjust the alignment for fixed-length SVE predicates.
2119 Align = 16;
2120 else if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
2121 VT->getVectorKind() == VectorKind::RVVFixedLengthMask ||
2122 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_1 ||
2123 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_2 ||
2124 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_4)
2125 // Adjust the alignment for fixed-length RVV vectors.
2126 Align = std::min<unsigned>(64, Width);
2127 break;
2128 }
2129
2130 case Type::ConstantMatrix: {
2131 const auto *MT = cast<ConstantMatrixType>(T);
2132 TypeInfo ElementInfo = getTypeInfo(MT->getElementType());
2133 // The internal layout of a matrix value is implementation defined.
2134 // Initially be ABI compatible with arrays with respect to alignment and
2135 // size.
2136 Width = ElementInfo.Width * MT->getNumRows() * MT->getNumColumns();
2137 Align = ElementInfo.Align;
2138 break;
2139 }
2140
2141 case Type::Builtin:
2142 switch (cast<BuiltinType>(T)->getKind()) {
2143 default: llvm_unreachable("Unknown builtin type!");
2144 case BuiltinType::Void:
2145 // GCC extension: alignof(void) = 8 bits.
2146 Width = 0;
2147 Align = 8;
2148 break;
2149 case BuiltinType::Bool:
2150 Width = Target->getBoolWidth();
2151 Align = Target->getBoolAlign();
2152 break;
2153 case BuiltinType::Char_S:
2154 case BuiltinType::Char_U:
2155 case BuiltinType::UChar:
2156 case BuiltinType::SChar:
2157 case BuiltinType::Char8:
2158 Width = Target->getCharWidth();
2159 Align = Target->getCharAlign();
2160 break;
2161 case BuiltinType::WChar_S:
2162 case BuiltinType::WChar_U:
2163 Width = Target->getWCharWidth();
2164 Align = Target->getWCharAlign();
2165 break;
2166 case BuiltinType::Char16:
2167 Width = Target->getChar16Width();
2168 Align = Target->getChar16Align();
2169 break;
2170 case BuiltinType::Char32:
2171 Width = Target->getChar32Width();
2172 Align = Target->getChar32Align();
2173 break;
2174 case BuiltinType::UShort:
2175 case BuiltinType::Short:
2176 Width = Target->getShortWidth();
2177 Align = Target->getShortAlign();
2178 break;
2179 case BuiltinType::UInt:
2180 case BuiltinType::Int:
2181 Width = Target->getIntWidth();
2182 Align = Target->getIntAlign();
2183 break;
2184 case BuiltinType::ULong:
2185 case BuiltinType::Long:
2186 Width = Target->getLongWidth();
2187 Align = Target->getLongAlign();
2188 break;
2189 case BuiltinType::ULongLong:
2190 case BuiltinType::LongLong:
2191 Width = Target->getLongLongWidth();
2192 Align = Target->getLongLongAlign();
2193 break;
2194 case BuiltinType::Int128:
2195 case BuiltinType::UInt128:
2196 Width = 128;
2197 Align = Target->getInt128Align();
2198 break;
2199 case BuiltinType::ShortAccum:
2200 case BuiltinType::UShortAccum:
2201 case BuiltinType::SatShortAccum:
2202 case BuiltinType::SatUShortAccum:
2203 Width = Target->getShortAccumWidth();
2204 Align = Target->getShortAccumAlign();
2205 break;
2206 case BuiltinType::Accum:
2207 case BuiltinType::UAccum:
2208 case BuiltinType::SatAccum:
2209 case BuiltinType::SatUAccum:
2210 Width = Target->getAccumWidth();
2211 Align = Target->getAccumAlign();
2212 break;
2213 case BuiltinType::LongAccum:
2214 case BuiltinType::ULongAccum:
2215 case BuiltinType::SatLongAccum:
2216 case BuiltinType::SatULongAccum:
2217 Width = Target->getLongAccumWidth();
2218 Align = Target->getLongAccumAlign();
2219 break;
2220 case BuiltinType::ShortFract:
2221 case BuiltinType::UShortFract:
2222 case BuiltinType::SatShortFract:
2223 case BuiltinType::SatUShortFract:
2224 Width = Target->getShortFractWidth();
2225 Align = Target->getShortFractAlign();
2226 break;
2227 case BuiltinType::Fract:
2228 case BuiltinType::UFract:
2229 case BuiltinType::SatFract:
2230 case BuiltinType::SatUFract:
2231 Width = Target->getFractWidth();
2232 Align = Target->getFractAlign();
2233 break;
2234 case BuiltinType::LongFract:
2235 case BuiltinType::ULongFract:
2236 case BuiltinType::SatLongFract:
2237 case BuiltinType::SatULongFract:
2238 Width = Target->getLongFractWidth();
2239 Align = Target->getLongFractAlign();
2240 break;
2241 case BuiltinType::BFloat16:
2242 if (Target->hasBFloat16Type()) {
2243 Width = Target->getBFloat16Width();
2244 Align = Target->getBFloat16Align();
2245 } else if ((getLangOpts().SYCLIsDevice ||
2246 (getLangOpts().OpenMP &&
2247 getLangOpts().OpenMPIsTargetDevice)) &&
2248 AuxTarget->hasBFloat16Type()) {
2249 Width = AuxTarget->getBFloat16Width();
2250 Align = AuxTarget->getBFloat16Align();
2251 }
2252 break;
2253 case BuiltinType::Float16:
2254 case BuiltinType::Half:
2255 if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
2256 !getLangOpts().OpenMPIsTargetDevice) {
2257 Width = Target->getHalfWidth();
2258 Align = Target->getHalfAlign();
2259 } else {
2260 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2261 "Expected OpenMP device compilation.");
2262 Width = AuxTarget->getHalfWidth();
2263 Align = AuxTarget->getHalfAlign();
2264 }
2265 break;
2266 case BuiltinType::Float:
2267 Width = Target->getFloatWidth();
2268 Align = Target->getFloatAlign();
2269 break;
2270 case BuiltinType::Double:
2271 Width = Target->getDoubleWidth();
2272 Align = Target->getDoubleAlign();
2273 break;
2274 case BuiltinType::Ibm128:
2275 Width = Target->getIbm128Width();
2276 Align = Target->getIbm128Align();
2277 break;
2278 case BuiltinType::LongDouble:
2279 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2280 (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() ||
2281 Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) {
2282 Width = AuxTarget->getLongDoubleWidth();
2283 Align = AuxTarget->getLongDoubleAlign();
2284 } else {
2285 Width = Target->getLongDoubleWidth();
2286 Align = Target->getLongDoubleAlign();
2287 }
2288 break;
2289 case BuiltinType::Float128:
2290 if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
2291 !getLangOpts().OpenMPIsTargetDevice) {
2292 Width = Target->getFloat128Width();
2293 Align = Target->getFloat128Align();
2294 } else {
2295 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2296 "Expected OpenMP device compilation.");
2297 Width = AuxTarget->getFloat128Width();
2298 Align = AuxTarget->getFloat128Align();
2299 }
2300 break;
2301 case BuiltinType::NullPtr:
2302 // C++ 3.9.1p11: sizeof(nullptr_t) == sizeof(void*)
2303 Width = Target->getPointerWidth(LangAS::Default);
2304 Align = Target->getPointerAlign(LangAS::Default);
2305 break;
2306 case BuiltinType::ObjCId:
2307 case BuiltinType::ObjCClass:
2308 case BuiltinType::ObjCSel:
2309 Width = Target->getPointerWidth(LangAS::Default);
2310 Align = Target->getPointerAlign(LangAS::Default);
2311 break;
2312 case BuiltinType::OCLSampler:
2313 case BuiltinType::OCLEvent:
2314 case BuiltinType::OCLClkEvent:
2315 case BuiltinType::OCLQueue:
2316 case BuiltinType::OCLReserveID:
2317#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2318 case BuiltinType::Id:
2319#include "clang/Basic/OpenCLImageTypes.def"
2320#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2321 case BuiltinType::Id:
2322#include "clang/Basic/OpenCLExtensionTypes.def"
2323 AS = Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
2324 Width = Target->getPointerWidth(AS);
2325 Align = Target->getPointerAlign(AS);
2326 break;
2327 // The SVE types are effectively target-specific. The length of an
2328 // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple
2329 // of 128 bits. There is one predicate bit for each vector byte, so the
2330 // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits.
2331 //
2332 // Because the length is only known at runtime, we use a dummy value
2333 // of 0 for the static length. The alignment values are those defined
2334 // by the Procedure Call Standard for the Arm Architecture.
2335#define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId) \
2336 case BuiltinType::Id: \
2337 Width = 0; \
2338 Align = 128; \
2339 break;
2340#define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId) \
2341 case BuiltinType::Id: \
2342 Width = 0; \
2343 Align = 16; \
2344 break;
2345#define SVE_OPAQUE_TYPE(Name, MangledName, Id, SingletonId) \
2346 case BuiltinType::Id: \
2347 Width = 0; \
2348 Align = 16; \
2349 break;
2350#define SVE_SCALAR_TYPE(Name, MangledName, Id, SingletonId, Bits) \
2351 case BuiltinType::Id: \
2352 Width = Bits; \
2353 Align = Bits; \
2354 break;
2355#include "clang/Basic/AArch64ACLETypes.def"
2356#define PPC_VECTOR_TYPE(Name, Id, Size) \
2357 case BuiltinType::Id: \
2358 Width = Size; \
2359 Align = Size; \
2360 break;
2361#include "clang/Basic/PPCTypes.def"
2362#define RVV_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, NF, IsSigned, \
2363 IsFP, IsBF) \
2364 case BuiltinType::Id: \
2365 Width = 0; \
2366 Align = ElBits; \
2367 break;
2368#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, ElKind) \
2369 case BuiltinType::Id: \
2370 Width = 0; \
2371 Align = 8; \
2372 break;
2373#include "clang/Basic/RISCVVTypes.def"
2374#define WASM_TYPE(Name, Id, SingletonId) \
2375 case BuiltinType::Id: \
2376 Width = 0; \
2377 Align = 8; \
2378 break;
2379#include "clang/Basic/WebAssemblyReferenceTypes.def"
2380#define AMDGPU_TYPE(NAME, ID, SINGLETONID, WIDTH, ALIGN) \
2381 case BuiltinType::ID: \
2382 Width = WIDTH; \
2383 Align = ALIGN; \
2384 break;
2385#include "clang/Basic/AMDGPUTypes.def"
2386#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
2387#include "clang/Basic/HLSLIntangibleTypes.def"
2388 Width = Target->getPointerWidth(LangAS::Default);
2389 Align = Target->getPointerAlign(LangAS::Default);
2390 break;
2391 }
2392 break;
2393 case Type::ObjCObjectPointer:
2394 Width = Target->getPointerWidth(LangAS::Default);
2395 Align = Target->getPointerAlign(LangAS::Default);
2396 break;
2397 case Type::BlockPointer:
2398 AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
2399 Width = Target->getPointerWidth(AS);
2400 Align = Target->getPointerAlign(AS);
2401 break;
2402 case Type::LValueReference:
2403 case Type::RValueReference:
2404 // alignof and sizeof should never enter this code path here, so we go
2405 // the pointer route.
2406 AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
2407 Width = Target->getPointerWidth(AS);
2408 Align = Target->getPointerAlign(AS);
2409 break;
2410 case Type::Pointer:
2411 AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
2412 Width = Target->getPointerWidth(AS);
2413 Align = Target->getPointerAlign(AS);
2414 break;
2415 case Type::MemberPointer: {
2416 const auto *MPT = cast<MemberPointerType>(T);
2417 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
2418 Width = MPI.Width;
2419 Align = MPI.Align;
2420 break;
2421 }
2422 case Type::Complex: {
2423 // Complex types have the same alignment as their elements, but twice the
2424 // size.
2425 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
2426 Width = EltInfo.Width * 2;
2427 Align = EltInfo.Align;
2428 break;
2429 }
2430 case Type::ObjCObject:
2431 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
2432 case Type::Adjusted:
2433 case Type::Decayed:
2434 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
2435 case Type::ObjCInterface: {
2436 const auto *ObjCI = cast<ObjCInterfaceType>(T);
2437 if (ObjCI->getDecl()->isInvalidDecl()) {
2438 Width = 8;
2439 Align = 8;
2440 break;
2441 }
2442 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2443 Width = toBits(Layout.getSize());
2444 Align = toBits(Layout.getAlignment());
2445 break;
2446 }
2447 case Type::BitInt: {
2448 const auto *EIT = cast<BitIntType>(T);
2449 Align = Target->getBitIntAlign(EIT->getNumBits());
2450 Width = Target->getBitIntWidth(EIT->getNumBits());
2451 break;
2452 }
2453 case Type::Record:
2454 case Type::Enum: {
2455 const auto *TT = cast<TagType>(T);
2456 const TagDecl *TD = TT->getDecl()->getDefinitionOrSelf();
2457
2458 if (TD->isInvalidDecl()) {
2459 Width = 8;
2460 Align = 8;
2461 break;
2462 }
2463
2464 if (isa<EnumType>(TT)) {
2465 const EnumDecl *ED = cast<EnumDecl>(TD);
2466 TypeInfo Info =
2468 if (unsigned AttrAlign = ED->getMaxAlignment()) {
2469 Info.Align = AttrAlign;
2471 }
2472 return Info;
2473 }
2474
2475 const auto *RD = cast<RecordDecl>(TD);
2476 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2477 Width = toBits(Layout.getSize());
2478 Align = toBits(Layout.getAlignment());
2479 AlignRequirement = RD->hasAttr<AlignedAttr>()
2481 : AlignRequirementKind::None;
2482 break;
2483 }
2484
2485 case Type::SubstTemplateTypeParm:
2487 getReplacementType().getTypePtr());
2488
2489 case Type::Auto:
2490 case Type::DeducedTemplateSpecialization: {
2491 const auto *A = cast<DeducedType>(T);
2492 assert(!A->getDeducedType().isNull() &&
2493 "cannot request the size of an undeduced or dependent auto type");
2494 return getTypeInfo(A->getDeducedType().getTypePtr());
2495 }
2496
2497 case Type::Paren:
2498 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
2499
2500 case Type::MacroQualified:
2501 return getTypeInfo(
2502 cast<MacroQualifiedType>(T)->getUnderlyingType().getTypePtr());
2503
2504 case Type::ObjCTypeParam:
2505 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
2506
2507 case Type::Using:
2508 return getTypeInfo(cast<UsingType>(T)->desugar().getTypePtr());
2509
2510 case Type::Typedef: {
2511 const auto *TT = cast<TypedefType>(T);
2512 TypeInfo Info = getTypeInfo(TT->desugar().getTypePtr());
2513 // If the typedef has an aligned attribute on it, it overrides any computed
2514 // alignment we have. This violates the GCC documentation (which says that
2515 // attribute(aligned) can only round up) but matches its implementation.
2516 if (unsigned AttrAlign = TT->getDecl()->getMaxAlignment()) {
2517 Align = AttrAlign;
2518 AlignRequirement = AlignRequirementKind::RequiredByTypedef;
2519 } else {
2520 Align = Info.Align;
2521 AlignRequirement = Info.AlignRequirement;
2522 }
2523 Width = Info.Width;
2524 break;
2525 }
2526
2527 case Type::Attributed:
2528 return getTypeInfo(
2529 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
2530
2531 case Type::CountAttributed:
2532 return getTypeInfo(cast<CountAttributedType>(T)->desugar().getTypePtr());
2533
2534 case Type::BTFTagAttributed:
2535 return getTypeInfo(
2536 cast<BTFTagAttributedType>(T)->getWrappedType().getTypePtr());
2537
2538 case Type::OverflowBehavior:
2539 return getTypeInfo(
2541
2542 case Type::HLSLAttributedResource:
2543 return getTypeInfo(
2544 cast<HLSLAttributedResourceType>(T)->getWrappedType().getTypePtr());
2545
2546 case Type::HLSLInlineSpirv: {
2547 const auto *ST = cast<HLSLInlineSpirvType>(T);
2548 // Size is specified in bytes, convert to bits
2549 Width = ST->getSize() * 8;
2550 Align = ST->getAlignment();
2551 if (Width == 0 && Align == 0) {
2552 // We are defaulting to laying out opaque SPIR-V types as 32-bit ints.
2553 Width = 32;
2554 Align = 32;
2555 }
2556 break;
2557 }
2558
2559 case Type::Atomic: {
2560 // Start with the base type information.
2561 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
2562 Width = Info.Width;
2563 Align = Info.Align;
2564
2565 if (!Width) {
2566 // An otherwise zero-sized type should still generate an
2567 // atomic operation.
2568 Width = Target->getCharWidth();
2569 assert(Align);
2570 } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2571 // If the size of the type doesn't exceed the platform's max
2572 // atomic promotion width, make the size and alignment more
2573 // favorable to atomic operations:
2574
2575 // Round the size up to a power of 2.
2576 Width = llvm::bit_ceil(Width);
2577
2578 // Set the alignment equal to the size.
2579 Align = static_cast<unsigned>(Width);
2580 }
2581 }
2582 break;
2583
2584 case Type::PredefinedSugar:
2585 return getTypeInfo(cast<PredefinedSugarType>(T)->desugar().getTypePtr());
2586
2587 case Type::Pipe:
2588 Width = Target->getPointerWidth(LangAS::opencl_global);
2589 Align = Target->getPointerAlign(LangAS::opencl_global);
2590 break;
2591 }
2592
2593 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
2594 return TypeInfo(Width, Align, AlignRequirement);
2595}
2596
2598 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
2599 if (I != MemoizedUnadjustedAlign.end())
2600 return I->second;
2601
2602 unsigned UnadjustedAlign;
2603 if (const auto *RT = T->getAsCanonical<RecordType>()) {
2604 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
2605 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2606 } else if (const auto *ObjCI = T->getAsCanonical<ObjCInterfaceType>()) {
2607 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2608 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2609 } else {
2610 UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType());
2611 }
2612
2613 MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2614 return UnadjustedAlign;
2615}
2616
2618 unsigned SimdAlign = llvm::OpenMPIRBuilder::getOpenMPDefaultSimdAlign(
2619 getTargetInfo().getTriple(), Target->getTargetOpts().FeatureMap);
2620 return SimdAlign;
2621}
2622
2623/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2625 return CharUnits::fromQuantity(BitSize / getCharWidth());
2626}
2627
2628/// toBits - Convert a size in characters to a size in characters.
2629int64_t ASTContext::toBits(CharUnits CharSize) const {
2630 return CharSize.getQuantity() * getCharWidth();
2631}
2632
2633/// getTypeSizeInChars - Return the size of the specified type, in characters.
2634/// This method does not work on incomplete types.
2641
2642/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
2643/// characters. This method does not work on incomplete types.
2650
2651/// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2652/// type, in characters, before alignment adjustments. This method does
2653/// not work on incomplete types.
2660
2661/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2662/// type for the current target in bits. This can be different than the ABI
2663/// alignment in cases where it is beneficial for performance or backwards
2664/// compatibility preserving to overalign a data type. (Note: despite the name,
2665/// the preferred alignment is ABI-impacting, and not an optimization.)
2666unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
2667 TypeInfo TI = getTypeInfo(T);
2668 unsigned ABIAlign = TI.Align;
2669
2670 T = T->getBaseElementTypeUnsafe();
2671
2672 // The preferred alignment of member pointers is that of a pointer.
2673 if (T->isMemberPointerType())
2674 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2675
2676 if (!Target->allowsLargerPreferedTypeAlignment())
2677 return ABIAlign;
2678
2679 if (const auto *RD = T->getAsRecordDecl()) {
2680 // When used as part of a typedef, or together with a 'packed' attribute,
2681 // the 'aligned' attribute can be used to decrease alignment. Note that the
2682 // 'packed' case is already taken into consideration when computing the
2683 // alignment, we only need to handle the typedef case here.
2685 RD->isInvalidDecl())
2686 return ABIAlign;
2687
2688 unsigned PreferredAlign = static_cast<unsigned>(
2689 toBits(getASTRecordLayout(RD).PreferredAlignment));
2690 assert(PreferredAlign >= ABIAlign &&
2691 "PreferredAlign should be at least as large as ABIAlign.");
2692 return PreferredAlign;
2693 }
2694
2695 // Double (and, for targets supporting AIX `power` alignment, long double) and
2696 // long long should be naturally aligned (despite requiring less alignment) if
2697 // possible.
2698 if (const auto *CT = T->getAs<ComplexType>())
2699 T = CT->getElementType().getTypePtr();
2700 if (const auto *ED = T->getAsEnumDecl())
2701 T = ED->getIntegerType().getTypePtr();
2702 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
2703 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2704 T->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2705 (T->isSpecificBuiltinType(BuiltinType::LongDouble) &&
2706 Target->defaultsToAIXPowerAlignment()))
2707 // Don't increase the alignment if an alignment attribute was specified on a
2708 // typedef declaration.
2709 if (!TI.isAlignRequired())
2710 return std::max(ABIAlign, (unsigned)getTypeSize(T));
2711
2712 return ABIAlign;
2713}
2714
2715/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2716/// for __attribute__((aligned)) on this target, to be used if no alignment
2717/// value is specified.
2721
2722/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2723/// to a global variable of the specified type.
2725 uint64_t TypeSize = getTypeSize(T.getTypePtr());
2726 return std::max(getPreferredTypeAlign(T),
2727 getMinGlobalAlignOfVar(TypeSize, VD));
2728}
2729
2730/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2731/// should be given to a global variable of the specified type.
2736
2738 const VarDecl *VD) const {
2739 // Make the default handling as that of a non-weak definition in the
2740 // current translation unit.
2741 bool HasNonWeakDef = !VD || (VD->hasDefinition() && !VD->isWeak());
2742 return getTargetInfo().getMinGlobalAlign(Size, HasNonWeakDef);
2743}
2744
2746 CharUnits Offset = CharUnits::Zero();
2747 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2748 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2749 Offset += Layout->getBaseClassOffset(Base);
2750 Layout = &getASTRecordLayout(Base);
2751 }
2752 return Offset;
2753}
2754
2756 const ValueDecl *MPD = MP.getMemberPointerDecl();
2759 bool DerivedMember = MP.isMemberPointerToDerivedMember();
2761 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
2762 const CXXRecordDecl *Base = RD;
2763 const CXXRecordDecl *Derived = Path[I];
2764 if (DerivedMember)
2765 std::swap(Base, Derived);
2767 RD = Path[I];
2768 }
2769 if (DerivedMember)
2771 return ThisAdjustment;
2772}
2773
2774/// DeepCollectObjCIvars -
2775/// This routine first collects all declared, but not synthesized, ivars in
2776/// super class and then collects all ivars, including those synthesized for
2777/// current class. This routine is used for implementation of current class
2778/// when all ivars, declared and synthesized are known.
2780 bool leafClass,
2782 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2783 DeepCollectObjCIvars(SuperClass, false, Ivars);
2784 if (!leafClass) {
2785 llvm::append_range(Ivars, OI->ivars());
2786 } else {
2787 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
2788 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
2789 Iv= Iv->getNextIvar())
2790 Ivars.push_back(Iv);
2791 }
2792}
2793
2794/// CollectInheritedProtocols - Collect all protocols in current class and
2795/// those inherited by it.
2798 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2799 // We can use protocol_iterator here instead of
2800 // all_referenced_protocol_iterator since we are walking all categories.
2801 for (auto *Proto : OI->all_referenced_protocols()) {
2802 CollectInheritedProtocols(Proto, Protocols);
2803 }
2804
2805 // Categories of this Interface.
2806 for (const auto *Cat : OI->visible_categories())
2807 CollectInheritedProtocols(Cat, Protocols);
2808
2809 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2810 while (SD) {
2811 CollectInheritedProtocols(SD, Protocols);
2812 SD = SD->getSuperClass();
2813 }
2814 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
2815 for (auto *Proto : OC->protocols()) {
2816 CollectInheritedProtocols(Proto, Protocols);
2817 }
2818 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
2819 // Insert the protocol.
2820 if (!Protocols.insert(
2821 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2822 return;
2823
2824 for (auto *Proto : OP->protocols())
2825 CollectInheritedProtocols(Proto, Protocols);
2826 }
2827}
2828
2830 const RecordDecl *RD,
2831 bool CheckIfTriviallyCopyable) {
2832 assert(RD->isUnion() && "Must be union type");
2833 CharUnits UnionSize =
2834 Context.getTypeSizeInChars(Context.getCanonicalTagType(RD));
2835
2836 for (const auto *Field : RD->fields()) {
2837 if (!Context.hasUniqueObjectRepresentations(Field->getType(),
2838 CheckIfTriviallyCopyable))
2839 return false;
2840 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2841 if (FieldSize != UnionSize)
2842 return false;
2843 }
2844 return !RD->field_empty();
2845}
2846
2847static int64_t getSubobjectOffset(const FieldDecl *Field,
2848 const ASTContext &Context,
2849 const clang::ASTRecordLayout & /*Layout*/) {
2850 return Context.getFieldOffset(Field);
2851}
2852
2853static int64_t getSubobjectOffset(const CXXRecordDecl *RD,
2854 const ASTContext &Context,
2855 const clang::ASTRecordLayout &Layout) {
2856 return Context.toBits(Layout.getBaseClassOffset(RD));
2857}
2858
2859static std::optional<int64_t>
2861 const RecordDecl *RD,
2862 bool CheckIfTriviallyCopyable);
2863
2864static std::optional<int64_t>
2865getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context,
2866 bool CheckIfTriviallyCopyable) {
2867 if (const auto *RD = Field->getType()->getAsRecordDecl();
2868 RD && !RD->isUnion())
2869 return structHasUniqueObjectRepresentations(Context, RD,
2870 CheckIfTriviallyCopyable);
2871
2872 // A _BitInt type may not be unique if it has padding bits
2873 // but if it is a bitfield the padding bits are not used.
2874 bool IsBitIntType = Field->getType()->isBitIntType();
2875 if (!Field->getType()->isReferenceType() && !IsBitIntType &&
2876 !Context.hasUniqueObjectRepresentations(Field->getType(),
2877 CheckIfTriviallyCopyable))
2878 return std::nullopt;
2879
2880 int64_t FieldSizeInBits =
2881 Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2882 if (Field->isBitField()) {
2883 // If we have explicit padding bits, they don't contribute bits
2884 // to the actual object representation, so return 0.
2885 if (Field->isUnnamedBitField())
2886 return 0;
2887
2888 int64_t BitfieldSize = Field->getBitWidthValue();
2889 if (IsBitIntType) {
2890 if ((unsigned)BitfieldSize >
2891 cast<BitIntType>(Field->getType())->getNumBits())
2892 return std::nullopt;
2893 } else if (BitfieldSize > FieldSizeInBits) {
2894 return std::nullopt;
2895 }
2896 FieldSizeInBits = BitfieldSize;
2897 } else if (IsBitIntType && !Context.hasUniqueObjectRepresentations(
2898 Field->getType(), CheckIfTriviallyCopyable)) {
2899 return std::nullopt;
2900 }
2901 return FieldSizeInBits;
2902}
2903
2904static std::optional<int64_t>
2906 bool CheckIfTriviallyCopyable) {
2907 return structHasUniqueObjectRepresentations(Context, RD,
2908 CheckIfTriviallyCopyable);
2909}
2910
2911template <typename RangeT>
2913 const RangeT &Subobjects, int64_t CurOffsetInBits,
2914 const ASTContext &Context, const clang::ASTRecordLayout &Layout,
2915 bool CheckIfTriviallyCopyable) {
2916 for (const auto *Subobject : Subobjects) {
2917 std::optional<int64_t> SizeInBits =
2918 getSubobjectSizeInBits(Subobject, Context, CheckIfTriviallyCopyable);
2919 if (!SizeInBits)
2920 return std::nullopt;
2921 if (*SizeInBits != 0) {
2922 int64_t Offset = getSubobjectOffset(Subobject, Context, Layout);
2923 if (Offset != CurOffsetInBits)
2924 return std::nullopt;
2925 CurOffsetInBits += *SizeInBits;
2926 }
2927 }
2928 return CurOffsetInBits;
2929}
2930
2931static std::optional<int64_t>
2933 const RecordDecl *RD,
2934 bool CheckIfTriviallyCopyable) {
2935 assert(!RD->isUnion() && "Must be struct/class type");
2936 const auto &Layout = Context.getASTRecordLayout(RD);
2937
2938 int64_t CurOffsetInBits = 0;
2939 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
2940 if (ClassDecl->isDynamicClass())
2941 return std::nullopt;
2942
2944 for (const auto &Base : ClassDecl->bases()) {
2945 // Empty types can be inherited from, and non-empty types can potentially
2946 // have tail padding, so just make sure there isn't an error.
2947 Bases.emplace_back(Base.getType()->getAsCXXRecordDecl());
2948 }
2949
2950 llvm::sort(Bases, [&](const CXXRecordDecl *L, const CXXRecordDecl *R) {
2951 return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R);
2952 });
2953
2954 std::optional<int64_t> OffsetAfterBases =
2956 Bases, CurOffsetInBits, Context, Layout, CheckIfTriviallyCopyable);
2957 if (!OffsetAfterBases)
2958 return std::nullopt;
2959 CurOffsetInBits = *OffsetAfterBases;
2960 }
2961
2962 std::optional<int64_t> OffsetAfterFields =
2964 RD->fields(), CurOffsetInBits, Context, Layout,
2965 CheckIfTriviallyCopyable);
2966 if (!OffsetAfterFields)
2967 return std::nullopt;
2968 CurOffsetInBits = *OffsetAfterFields;
2969
2970 return CurOffsetInBits;
2971}
2972
2974 QualType Ty, bool CheckIfTriviallyCopyable) const {
2975 // C++17 [meta.unary.prop]:
2976 // The predicate condition for a template specialization
2977 // has_unique_object_representations<T> shall be satisfied if and only if:
2978 // (9.1) - T is trivially copyable, and
2979 // (9.2) - any two objects of type T with the same value have the same
2980 // object representation, where:
2981 // - two objects of array or non-union class type are considered to have
2982 // the same value if their respective sequences of direct subobjects
2983 // have the same values, and
2984 // - two objects of union type are considered to have the same value if
2985 // they have the same active member and the corresponding members have
2986 // the same value.
2987 // The set of scalar types for which this condition holds is
2988 // implementation-defined. [ Note: If a type has padding bits, the condition
2989 // does not hold; otherwise, the condition holds true for unsigned integral
2990 // types. -- end note ]
2991 assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
2992
2993 // Arrays are unique only if their element type is unique.
2994 if (Ty->isArrayType())
2996 CheckIfTriviallyCopyable);
2997
2998 assert((Ty->isVoidType() || !Ty->isIncompleteType()) &&
2999 "hasUniqueObjectRepresentations should not be called with an "
3000 "incomplete type");
3001
3002 // (9.1) - T is trivially copyable...
3003 if (CheckIfTriviallyCopyable && !Ty.isTriviallyCopyableType(*this))
3004 return false;
3005
3006 // All integrals and enums are unique.
3007 if (Ty->isIntegralOrEnumerationType()) {
3008 // Address discriminated integer types are not unique.
3010 return false;
3011 // Except _BitInt types that have padding bits.
3012 if (const auto *BIT = Ty->getAs<BitIntType>())
3013 return getTypeSize(BIT) == BIT->getNumBits();
3014
3015 return true;
3016 }
3017
3018 // All other pointers are unique.
3019 if (Ty->isPointerType())
3021
3022 if (const auto *MPT = Ty->getAs<MemberPointerType>())
3023 return !ABI->getMemberPointerInfo(MPT).HasPadding;
3024
3025 if (const auto *Record = Ty->getAsRecordDecl()) {
3026 if (Record->isInvalidDecl())
3027 return false;
3028
3029 if (Record->isUnion())
3031 CheckIfTriviallyCopyable);
3032
3033 std::optional<int64_t> StructSize = structHasUniqueObjectRepresentations(
3034 *this, Record, CheckIfTriviallyCopyable);
3035
3036 return StructSize && *StructSize == static_cast<int64_t>(getTypeSize(Ty));
3037 }
3038
3039 // FIXME: More cases to handle here (list by rsmith):
3040 // vectors (careful about, eg, vector of 3 foo)
3041 // _Complex int and friends
3042 // _Atomic T
3043 // Obj-C block pointers
3044 // Obj-C object pointers
3045 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
3046 // clk_event_t, queue_t, reserve_id_t)
3047 // There're also Obj-C class types and the Obj-C selector type, but I think it
3048 // makes sense for those to return false here.
3049
3050 return false;
3051}
3052
3054 unsigned count = 0;
3055 // Count ivars declared in class extension.
3056 for (const auto *Ext : OI->known_extensions())
3057 count += Ext->ivar_size();
3058
3059 // Count ivar defined in this class's implementation. This
3060 // includes synthesized ivars.
3061 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
3062 count += ImplDecl->ivar_size();
3063
3064 return count;
3065}
3066
3068 if (!E)
3069 return false;
3070
3071 // nullptr_t is always treated as null.
3072 if (E->getType()->isNullPtrType()) return true;
3073
3074 if (E->getType()->isAnyPointerType() &&
3077 return true;
3078
3079 // Unfortunately, __null has type 'int'.
3080 if (isa<GNUNullExpr>(E)) return true;
3081
3082 return false;
3083}
3084
3085/// Get the implementation of ObjCInterfaceDecl, or nullptr if none
3086/// exists.
3088 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
3089 I = ObjCImpls.find(D);
3090 if (I != ObjCImpls.end())
3091 return cast<ObjCImplementationDecl>(I->second);
3092 return nullptr;
3093}
3094
3095/// Get the implementation of ObjCCategoryDecl, or nullptr if none
3096/// exists.
3098 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
3099 I = ObjCImpls.find(D);
3100 if (I != ObjCImpls.end())
3101 return cast<ObjCCategoryImplDecl>(I->second);
3102 return nullptr;
3103}
3104
3105/// Set the implementation of ObjCInterfaceDecl.
3107 ObjCImplementationDecl *ImplD) {
3108 assert(IFaceD && ImplD && "Passed null params");
3109 ObjCImpls[IFaceD] = ImplD;
3110}
3111
3112/// Set the implementation of ObjCCategoryDecl.
3114 ObjCCategoryImplDecl *ImplD) {
3115 assert(CatD && ImplD && "Passed null params");
3116 ObjCImpls[CatD] = ImplD;
3117}
3118
3119const ObjCMethodDecl *
3121 return ObjCMethodRedecls.lookup(MD);
3122}
3123
3125 const ObjCMethodDecl *Redecl) {
3126 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
3127 ObjCMethodRedecls[MD] = Redecl;
3128}
3129
3131 const NamedDecl *ND) const {
3132 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
3133 return ID;
3134 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
3135 return CD->getClassInterface();
3136 if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
3137 return IMD->getClassInterface();
3138
3139 return nullptr;
3140}
3141
3142/// Get the copy initialization expression of VarDecl, or nullptr if
3143/// none exists.
3145 assert(VD && "Passed null params");
3146 assert(VD->hasAttr<BlocksAttr>() &&
3147 "getBlockVarCopyInits - not __block var");
3148 auto I = BlockVarCopyInits.find(VD);
3149 if (I != BlockVarCopyInits.end())
3150 return I->second;
3151 return {nullptr, false};
3152}
3153
3154/// Set the copy initialization expression of a block var decl.
3156 bool CanThrow) {
3157 assert(VD && CopyExpr && "Passed null params");
3158 assert(VD->hasAttr<BlocksAttr>() &&
3159 "setBlockVarCopyInits - not __block var");
3160 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
3161}
3162
3164 unsigned DataSize) const {
3165 if (!DataSize)
3166 DataSize = TypeLoc::getFullDataSizeForType(T);
3167 else
3168 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
3169 "incorrect data size provided to CreateTypeSourceInfo!");
3170
3171 auto *TInfo =
3172 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
3173 new (TInfo) TypeSourceInfo(T, DataSize);
3174 return TInfo;
3175}
3176
3178 SourceLocation L) const {
3180 TSI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
3181 return TSI;
3182}
3183
3184const ASTRecordLayout &
3186 return getObjCLayout(D);
3187}
3188
3191 bool &AnyNonCanonArgs) {
3192 SmallVector<TemplateArgument, 16> CanonArgs(Args);
3193 AnyNonCanonArgs |= C.canonicalizeTemplateArguments(CanonArgs);
3194 return CanonArgs;
3195}
3196
3199 bool AnyNonCanonArgs = false;
3200 for (auto &Arg : Args) {
3201 TemplateArgument OrigArg = Arg;
3203 AnyNonCanonArgs |= !Arg.structurallyEquals(OrigArg);
3204 }
3205 return AnyNonCanonArgs;
3206}
3207
3208//===----------------------------------------------------------------------===//
3209// Type creation/memoization methods
3210//===----------------------------------------------------------------------===//
3211
3213ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
3214 unsigned fastQuals = quals.getFastQualifiers();
3215 quals.removeFastQualifiers();
3216
3217 // Check if we've already instantiated this type.
3218 llvm::FoldingSetNodeID ID;
3219 ExtQuals::Profile(ID, baseType, quals);
3220 void *insertPos = nullptr;
3221 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
3222 assert(eq->getQualifiers() == quals);
3223 return QualType(eq, fastQuals);
3224 }
3225
3226 // If the base type is not canonical, make the appropriate canonical type.
3227 QualType canon;
3228 if (!baseType->isCanonicalUnqualified()) {
3229 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
3230 canonSplit.Quals.addConsistentQualifiers(quals);
3231 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
3232
3233 // Re-find the insert position.
3234 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
3235 }
3236
3237 auto *eq = new (*this, alignof(ExtQuals)) ExtQuals(baseType, canon, quals);
3238 ExtQualNodes.InsertNode(eq, insertPos);
3239 return QualType(eq, fastQuals);
3240}
3241
3243 LangAS AddressSpace) const {
3244 QualType CanT = getCanonicalType(T);
3245 if (CanT.getAddressSpace() == AddressSpace)
3246 return T;
3247
3248 // If we are composing extended qualifiers together, merge together
3249 // into one ExtQuals node.
3250 QualifierCollector Quals;
3251 const Type *TypeNode = Quals.strip(T);
3252
3253 // If this type already has an address space specified, it cannot get
3254 // another one.
3255 assert(!Quals.hasAddressSpace() &&
3256 "Type cannot be in multiple addr spaces!");
3257 Quals.addAddressSpace(AddressSpace);
3258
3259 return getExtQualType(TypeNode, Quals);
3260}
3261
3263 // If the type is not qualified with an address space, just return it
3264 // immediately.
3265 if (!T.hasAddressSpace())
3266 return T;
3267
3268 QualifierCollector Quals;
3269 const Type *TypeNode;
3270 // For arrays, strip the qualifier off the element type, then reconstruct the
3271 // array type
3272 if (T.getTypePtr()->isArrayType()) {
3273 T = getUnqualifiedArrayType(T, Quals);
3274 TypeNode = T.getTypePtr();
3275 } else {
3276 // If we are composing extended qualifiers together, merge together
3277 // into one ExtQuals node.
3278 while (T.hasAddressSpace()) {
3279 TypeNode = Quals.strip(T);
3280
3281 // If the type no longer has an address space after stripping qualifiers,
3282 // jump out.
3283 if (!QualType(TypeNode, 0).hasAddressSpace())
3284 break;
3285
3286 // There might be sugar in the way. Strip it and try again.
3287 T = T.getSingleStepDesugaredType(*this);
3288 }
3289 }
3290
3291 Quals.removeAddressSpace();
3292
3293 // Removal of the address space can mean there are no longer any
3294 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
3295 // or required.
3296 if (Quals.hasNonFastQualifiers())
3297 return getExtQualType(TypeNode, Quals);
3298 else
3299 return QualType(TypeNode, Quals.getFastQualifiers());
3300}
3301
3302uint16_t
3304 assert(RD->isPolymorphic() &&
3305 "Attempted to get vtable pointer discriminator on a monomorphic type");
3306 std::unique_ptr<MangleContext> MC(createMangleContext());
3307 SmallString<256> Str;
3308 llvm::raw_svector_ostream Out(Str);
3309 MC->mangleCXXVTable(RD, Out);
3310 return llvm::getPointerAuthStableSipHash(Str);
3311}
3312
3313/// Encode a function type for use in the discriminator of a function pointer
3314/// type. We can't use the itanium scheme for this since C has quite permissive
3315/// rules for type compatibility that we need to be compatible with.
3316///
3317/// Formally, this function associates every function pointer type T with an
3318/// encoded string E(T). Let the equivalence relation T1 ~ T2 be defined as
3319/// E(T1) == E(T2). E(T) is part of the ABI of values of type T. C type
3320/// compatibility requires equivalent treatment under the ABI, so
3321/// CCompatible(T1, T2) must imply E(T1) == E(T2), that is, CCompatible must be
3322/// a subset of ~. Crucially, however, it must be a proper subset because
3323/// CCompatible is not an equivalence relation: for example, int[] is compatible
3324/// with both int[1] and int[2], but the latter are not compatible with each
3325/// other. Therefore this encoding function must be careful to only distinguish
3326/// types if there is no third type with which they are both required to be
3327/// compatible.
3329 raw_ostream &OS, QualType QT) {
3330 // FIXME: Consider address space qualifiers.
3331 const Type *T = QT.getCanonicalType().getTypePtr();
3332
3333 // FIXME: Consider using the C++ type mangling when we encounter a construct
3334 // that is incompatible with C.
3335
3336 switch (T->getTypeClass()) {
3337 case Type::Atomic:
3339 Ctx, OS, cast<AtomicType>(T)->getValueType());
3340
3341 case Type::LValueReference:
3342 OS << "R";
3345 return;
3346 case Type::RValueReference:
3347 OS << "O";
3350 return;
3351
3352 case Type::Pointer:
3353 // C11 6.7.6.1p2:
3354 // For two pointer types to be compatible, both shall be identically
3355 // qualified and both shall be pointers to compatible types.
3356 // FIXME: we should also consider pointee types.
3357 OS << "P";
3358 return;
3359
3360 case Type::ObjCObjectPointer:
3361 case Type::BlockPointer:
3362 OS << "P";
3363 return;
3364
3365 case Type::Complex:
3366 OS << "C";
3368 Ctx, OS, cast<ComplexType>(T)->getElementType());
3369
3370 case Type::VariableArray:
3371 case Type::ConstantArray:
3372 case Type::IncompleteArray:
3373 case Type::ArrayParameter:
3374 // C11 6.7.6.2p6:
3375 // For two array types to be compatible, both shall have compatible
3376 // element types, and if both size specifiers are present, and are integer
3377 // constant expressions, then both size specifiers shall have the same
3378 // constant value [...]
3379 //
3380 // So since ElemType[N] has to be compatible ElemType[], we can't encode the
3381 // width of the array.
3382 OS << "A";
3384 Ctx, OS, cast<ArrayType>(T)->getElementType());
3385
3386 case Type::ObjCInterface:
3387 case Type::ObjCObject:
3388 OS << "<objc_object>";
3389 return;
3390
3391 case Type::Enum: {
3392 // C11 6.7.2.2p4:
3393 // Each enumerated type shall be compatible with char, a signed integer
3394 // type, or an unsigned integer type.
3395 //
3396 // So we have to treat enum types as integers.
3397 QualType UnderlyingType = T->castAsEnumDecl()->getIntegerType();
3399 Ctx, OS, UnderlyingType.isNull() ? Ctx.IntTy : UnderlyingType);
3400 }
3401
3402 case Type::FunctionNoProto:
3403 case Type::FunctionProto: {
3404 // C11 6.7.6.3p15:
3405 // For two function types to be compatible, both shall specify compatible
3406 // return types. Moreover, the parameter type lists, if both are present,
3407 // shall agree in the number of parameters and in the use of the ellipsis
3408 // terminator; corresponding parameters shall have compatible types.
3409 //
3410 // That paragraph goes on to describe how unprototyped functions are to be
3411 // handled, which we ignore here. Unprototyped function pointers are hashed
3412 // as though they were prototyped nullary functions since thats probably
3413 // what the user meant. This behavior is non-conforming.
3414 // FIXME: If we add a "custom discriminator" function type attribute we
3415 // should encode functions as their discriminators.
3416 OS << "F";
3417 const auto *FuncType = cast<FunctionType>(T);
3418 encodeTypeForFunctionPointerAuth(Ctx, OS, FuncType->getReturnType());
3419 if (const auto *FPT = dyn_cast<FunctionProtoType>(FuncType)) {
3420 for (QualType Param : FPT->param_types()) {
3421 Param = Ctx.getSignatureParameterType(Param);
3422 encodeTypeForFunctionPointerAuth(Ctx, OS, Param);
3423 }
3424 if (FPT->isVariadic())
3425 OS << "z";
3426 }
3427 OS << "E";
3428 return;
3429 }
3430
3431 case Type::MemberPointer: {
3432 OS << "M";
3433 const auto *MPT = T->castAs<MemberPointerType>();
3435 Ctx, OS, QualType(MPT->getQualifier().getAsType(), 0));
3436 encodeTypeForFunctionPointerAuth(Ctx, OS, MPT->getPointeeType());
3437 return;
3438 }
3439 case Type::ExtVector:
3440 case Type::Vector:
3441 OS << "Dv" << Ctx.getTypeSizeInChars(T).getQuantity();
3442 break;
3443
3444 // Don't bother discriminating based on these types.
3445 case Type::Pipe:
3446 case Type::BitInt:
3447 case Type::ConstantMatrix:
3448 OS << "?";
3449 return;
3450
3451 case Type::Builtin: {
3452 const auto *BTy = T->castAs<BuiltinType>();
3453 switch (BTy->getKind()) {
3454#define SIGNED_TYPE(Id, SingletonId) \
3455 case BuiltinType::Id: \
3456 OS << "i"; \
3457 return;
3458#define UNSIGNED_TYPE(Id, SingletonId) \
3459 case BuiltinType::Id: \
3460 OS << "i"; \
3461 return;
3462#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
3463#define BUILTIN_TYPE(Id, SingletonId)
3464#include "clang/AST/BuiltinTypes.def"
3465 llvm_unreachable("placeholder types should not appear here.");
3466
3467 case BuiltinType::Half:
3468 OS << "Dh";
3469 return;
3470 case BuiltinType::Float:
3471 OS << "f";
3472 return;
3473 case BuiltinType::Double:
3474 OS << "d";
3475 return;
3476 case BuiltinType::LongDouble:
3477 OS << "e";
3478 return;
3479 case BuiltinType::Float16:
3480 OS << "DF16_";
3481 return;
3482 case BuiltinType::Float128:
3483 OS << "g";
3484 return;
3485
3486 case BuiltinType::Void:
3487 OS << "v";
3488 return;
3489
3490 case BuiltinType::ObjCId:
3491 case BuiltinType::ObjCClass:
3492 case BuiltinType::ObjCSel:
3493 case BuiltinType::NullPtr:
3494 OS << "P";
3495 return;
3496
3497 // Don't bother discriminating based on OpenCL types.
3498 case BuiltinType::OCLSampler:
3499 case BuiltinType::OCLEvent:
3500 case BuiltinType::OCLClkEvent:
3501 case BuiltinType::OCLQueue:
3502 case BuiltinType::OCLReserveID:
3503 case BuiltinType::BFloat16:
3504 case BuiltinType::VectorQuad:
3505 case BuiltinType::VectorPair:
3506 case BuiltinType::DMR1024:
3507 case BuiltinType::DMR2048:
3508 OS << "?";
3509 return;
3510
3511 // Don't bother discriminating based on these seldom-used types.
3512 case BuiltinType::Ibm128:
3513 return;
3514#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
3515 case BuiltinType::Id: \
3516 return;
3517#include "clang/Basic/OpenCLImageTypes.def"
3518#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
3519 case BuiltinType::Id: \
3520 return;
3521#include "clang/Basic/OpenCLExtensionTypes.def"
3522#define SVE_TYPE(Name, Id, SingletonId) \
3523 case BuiltinType::Id: \
3524 return;
3525#include "clang/Basic/AArch64ACLETypes.def"
3526#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
3527 case BuiltinType::Id: \
3528 return;
3529#include "clang/Basic/HLSLIntangibleTypes.def"
3530 case BuiltinType::Dependent:
3531 llvm_unreachable("should never get here");
3532#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
3533#include "clang/Basic/AMDGPUTypes.def"
3534 case BuiltinType::WasmExternRef:
3535#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
3536#include "clang/Basic/RISCVVTypes.def"
3537 llvm_unreachable("not yet implemented");
3538 }
3539 llvm_unreachable("should never get here");
3540 }
3541 case Type::Record: {
3542 const RecordDecl *RD = T->castAsCanonical<RecordType>()->getDecl();
3543 const IdentifierInfo *II = RD->getIdentifier();
3544
3545 // In C++, an immediate typedef of an anonymous struct or union
3546 // is considered to name it for ODR purposes, but C's specification
3547 // of type compatibility does not have a similar rule. Using the typedef
3548 // name in function type discriminators anyway, as we do here,
3549 // therefore technically violates the C standard: two function pointer
3550 // types defined in terms of two typedef'd anonymous structs with
3551 // different names are formally still compatible, but we are assigning
3552 // them different discriminators and therefore incompatible ABIs.
3553 //
3554 // This is a relatively minor violation that significantly improves
3555 // discrimination in some cases and has not caused problems in
3556 // practice. Regardless, it is now part of the ABI in places where
3557 // function type discrimination is used, and it can no longer be
3558 // changed except on new platforms.
3559
3560 if (!II)
3561 if (const TypedefNameDecl *Typedef = RD->getTypedefNameForAnonDecl())
3562 II = Typedef->getDeclName().getAsIdentifierInfo();
3563
3564 if (!II) {
3565 OS << "<anonymous_record>";
3566 return;
3567 }
3568 OS << II->getLength() << II->getName();
3569 return;
3570 }
3571 case Type::HLSLAttributedResource:
3572 case Type::HLSLInlineSpirv:
3573 llvm_unreachable("should never get here");
3574 break;
3575 case Type::OverflowBehavior:
3576 llvm_unreachable("should never get here");
3577 break;
3578 case Type::DeducedTemplateSpecialization:
3579 case Type::Auto:
3580#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3581#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3582#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3583#define ABSTRACT_TYPE(Class, Base)
3584#define TYPE(Class, Base)
3585#include "clang/AST/TypeNodes.inc"
3586 llvm_unreachable("unexpected non-canonical or dependent type!");
3587 return;
3588 }
3589}
3590
3592 assert(!T->isDependentType() &&
3593 "cannot compute type discriminator of a dependent type");
3594 SmallString<256> Str;
3595 llvm::raw_svector_ostream Out(Str);
3596
3597 if (T->isFunctionPointerType() || T->isFunctionReferenceType())
3598 T = T->getPointeeType();
3599
3600 if (T->isFunctionType()) {
3601 encodeTypeForFunctionPointerAuth(*this, Out, T);
3602 } else {
3603 T = T.getUnqualifiedType();
3604 // Calls to member function pointers don't need to worry about
3605 // language interop or the laxness of the C type compatibility rules.
3606 // We just mangle the member pointer type directly, which is
3607 // implicitly much stricter about type matching. However, we do
3608 // strip any top-level exception specification before this mangling.
3609 // C++23 requires calls to work when the function type is convertible
3610 // to the pointer type by a function pointer conversion, which can
3611 // change the exception specification. This does not technically
3612 // require the exception specification to not affect representation,
3613 // because the function pointer conversion is still always a direct
3614 // value conversion and therefore an opportunity to resign the
3615 // pointer. (This is in contrast to e.g. qualification conversions,
3616 // which can be applied in nested pointer positions, effectively
3617 // requiring qualified and unqualified representations to match.)
3618 // However, it is pragmatic to ignore exception specifications
3619 // because it allows a certain amount of `noexcept` mismatching
3620 // to not become a visible ODR problem. This also leaves some
3621 // room for the committee to add laxness to function pointer
3622 // conversions in future standards.
3623 if (auto *MPT = T->getAs<MemberPointerType>())
3624 if (MPT->isMemberFunctionPointer()) {
3625 QualType PointeeType = MPT->getPointeeType();
3626 if (PointeeType->castAs<FunctionProtoType>()->getExceptionSpecType() !=
3627 EST_None) {
3629 T = getMemberPointerType(FT, MPT->getQualifier(),
3630 MPT->getMostRecentCXXRecordDecl());
3631 }
3632 }
3633 std::unique_ptr<MangleContext> MC(createMangleContext());
3634 MC->mangleCanonicalTypeName(T, Out);
3635 }
3636
3637 return llvm::getPointerAuthStableSipHash(Str);
3638}
3639
3641 Qualifiers::GC GCAttr) const {
3642 QualType CanT = getCanonicalType(T);
3643 if (CanT.getObjCGCAttr() == GCAttr)
3644 return T;
3645
3646 if (const auto *ptr = T->getAs<PointerType>()) {
3647 QualType Pointee = ptr->getPointeeType();
3648 if (Pointee->isAnyPointerType()) {
3649 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
3650 return getPointerType(ResultType);
3651 }
3652 }
3653
3654 // If we are composing extended qualifiers together, merge together
3655 // into one ExtQuals node.
3656 QualifierCollector Quals;
3657 const Type *TypeNode = Quals.strip(T);
3658
3659 // If this type already has an ObjCGC specified, it cannot get
3660 // another one.
3661 assert(!Quals.hasObjCGCAttr() &&
3662 "Type cannot have multiple ObjCGCs!");
3663 Quals.addObjCGCAttr(GCAttr);
3664
3665 return getExtQualType(TypeNode, Quals);
3666}
3667
3669 if (const PointerType *Ptr = T->getAs<PointerType>()) {
3670 QualType Pointee = Ptr->getPointeeType();
3671 if (isPtrSizeAddressSpace(Pointee.getAddressSpace())) {
3672 return getPointerType(removeAddrSpaceQualType(Pointee));
3673 }
3674 }
3675 return T;
3676}
3677
3679 QualType WrappedTy, Expr *CountExpr, bool CountInBytes, bool OrNull,
3680 ArrayRef<TypeCoupledDeclRefInfo> DependentDecls) const {
3681 assert(WrappedTy->isPointerType() || WrappedTy->isArrayType());
3682
3683 llvm::FoldingSetNodeID ID;
3684 CountAttributedType::Profile(ID, WrappedTy, CountExpr, CountInBytes, OrNull);
3685
3686 void *InsertPos = nullptr;
3687 CountAttributedType *CATy =
3688 CountAttributedTypes.FindNodeOrInsertPos(ID, InsertPos);
3689 if (CATy)
3690 return QualType(CATy, 0);
3691
3692 QualType CanonTy = getCanonicalType(WrappedTy);
3693 size_t Size = CountAttributedType::totalSizeToAlloc<TypeCoupledDeclRefInfo>(
3694 DependentDecls.size());
3696 new (CATy) CountAttributedType(WrappedTy, CanonTy, CountExpr, CountInBytes,
3697 OrNull, DependentDecls);
3698 Types.push_back(CATy);
3699 CountAttributedTypes.InsertNode(CATy, InsertPos);
3700
3701 return QualType(CATy, 0);
3702}
3703
3706 llvm::function_ref<QualType(QualType)> Adjust) const {
3707 switch (Orig->getTypeClass()) {
3708 case Type::Attributed: {
3709 const auto *AT = cast<AttributedType>(Orig);
3710 return getAttributedType(AT->getAttrKind(),
3711 adjustType(AT->getModifiedType(), Adjust),
3712 adjustType(AT->getEquivalentType(), Adjust),
3713 AT->getAttr());
3714 }
3715
3716 case Type::BTFTagAttributed: {
3717 const auto *BTFT = dyn_cast<BTFTagAttributedType>(Orig);
3718 return getBTFTagAttributedType(BTFT->getAttr(),
3719 adjustType(BTFT->getWrappedType(), Adjust));
3720 }
3721
3722 case Type::OverflowBehavior: {
3723 const auto *OB = dyn_cast<OverflowBehaviorType>(Orig);
3724 return getOverflowBehaviorType(OB->getBehaviorKind(),
3725 adjustType(OB->getUnderlyingType(), Adjust));
3726 }
3727
3728 case Type::Paren:
3729 return getParenType(
3730 adjustType(cast<ParenType>(Orig)->getInnerType(), Adjust));
3731
3732 case Type::Adjusted: {
3733 const auto *AT = cast<AdjustedType>(Orig);
3734 return getAdjustedType(AT->getOriginalType(),
3735 adjustType(AT->getAdjustedType(), Adjust));
3736 }
3737
3738 case Type::MacroQualified: {
3739 const auto *MQT = cast<MacroQualifiedType>(Orig);
3740 return getMacroQualifiedType(adjustType(MQT->getUnderlyingType(), Adjust),
3741 MQT->getMacroIdentifier());
3742 }
3743
3744 default:
3745 return Adjust(Orig);
3746 }
3747}
3748
3750 FunctionType::ExtInfo Info) {
3751 if (T->getExtInfo() == Info)
3752 return T;
3753
3755 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
3756 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
3757 } else {
3758 const auto *FPT = cast<FunctionProtoType>(T);
3759 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
3760 EPI.ExtInfo = Info;
3761 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
3762 }
3763
3764 return cast<FunctionType>(Result.getTypePtr());
3765}
3766
3768 QualType ResultType) {
3769 return adjustType(FunctionType, [&](QualType Orig) {
3770 if (const auto *FNPT = Orig->getAs<FunctionNoProtoType>())
3771 return getFunctionNoProtoType(ResultType, FNPT->getExtInfo());
3772
3773 const auto *FPT = Orig->castAs<FunctionProtoType>();
3774 return getFunctionType(ResultType, FPT->getParamTypes(),
3775 FPT->getExtProtoInfo());
3776 });
3777}
3778
3780 QualType ResultType) {
3781 FD = FD->getMostRecentDecl();
3782 while (true) {
3783 FD->setType(adjustFunctionResultType(FD->getType(), ResultType));
3784 if (FunctionDecl *Next = FD->getPreviousDecl())
3785 FD = Next;
3786 else
3787 break;
3788 }
3790 L->DeducedReturnType(FD, ResultType);
3791}
3792
3793/// Get a function type and produce the equivalent function type with the
3794/// specified exception specification. Type sugar that can be present on a
3795/// declaration of a function with an exception specification is permitted
3796/// and preserved. Other type sugar (for instance, typedefs) is not.
3798 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const {
3799 return adjustType(Orig, [&](QualType Ty) {
3800 const auto *Proto = Ty->castAs<FunctionProtoType>();
3801 return getFunctionType(Proto->getReturnType(), Proto->getParamTypes(),
3802 Proto->getExtProtoInfo().withExceptionSpec(ESI));
3803 });
3804}
3805
3813
3815 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3816 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3817 SmallVector<QualType, 16> Args(Proto->param_types().size());
3818 for (unsigned i = 0, n = Args.size(); i != n; ++i)
3819 Args[i] = removePtrSizeAddrSpace(Proto->param_types()[i]);
3820 return getFunctionType(RetTy, Args, Proto->getExtProtoInfo());
3821 }
3822
3823 if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) {
3824 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3825 return getFunctionNoProtoType(RetTy, Proto->getExtInfo());
3826 }
3827
3828 return T;
3829}
3830
3836
3838 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3839 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3840 EPI.ExtParameterInfos = nullptr;
3841 return getFunctionType(Proto->getReturnType(), Proto->param_types(), EPI);
3842 }
3843 return T;
3844}
3845
3851
3854 bool AsWritten) {
3855 // Update the type.
3856 QualType Updated =
3858 FD->setType(Updated);
3859
3860 if (!AsWritten)
3861 return;
3862
3863 // Update the type in the type source information too.
3864 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
3865 // If the type and the type-as-written differ, we may need to update
3866 // the type-as-written too.
3867 if (TSInfo->getType() != FD->getType())
3868 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
3869
3870 // FIXME: When we get proper type location information for exceptions,
3871 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
3872 // up the TypeSourceInfo;
3873 assert(TypeLoc::getFullDataSizeForType(Updated) ==
3874 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
3875 "TypeLoc size mismatch from updating exception specification");
3876 TSInfo->overrideType(Updated);
3877 }
3878}
3879
3880/// getComplexType - Return the uniqued reference to the type for a complex
3881/// number with the specified element type.
3883 // Unique pointers, to guarantee there is only one pointer of a particular
3884 // structure.
3885 llvm::FoldingSetNodeID ID;
3886 ComplexType::Profile(ID, T);
3887
3888 void *InsertPos = nullptr;
3889 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
3890 return QualType(CT, 0);
3891
3892 // If the pointee type isn't canonical, this won't be a canonical type either,
3893 // so fill in the canonical type field.
3894 QualType Canonical;
3895 if (!T.isCanonical()) {
3896 Canonical = getComplexType(getCanonicalType(T));
3897
3898 // Get the new insert position for the node we care about.
3899 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
3900 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3901 }
3902 auto *New = new (*this, alignof(ComplexType)) ComplexType(T, Canonical);
3903 Types.push_back(New);
3904 ComplexTypes.InsertNode(New, InsertPos);
3905 return QualType(New, 0);
3906}
3907
3908/// getPointerType - Return the uniqued reference to the type for a pointer to
3909/// the specified type.
3911 // Unique pointers, to guarantee there is only one pointer of a particular
3912 // structure.
3913 llvm::FoldingSetNodeID ID;
3914 PointerType::Profile(ID, T);
3915
3916 void *InsertPos = nullptr;
3917 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3918 return QualType(PT, 0);
3919
3920 // If the pointee type isn't canonical, this won't be a canonical type either,
3921 // so fill in the canonical type field.
3922 QualType Canonical;
3923 if (!T.isCanonical()) {
3924 Canonical = getPointerType(getCanonicalType(T));
3925
3926 // Get the new insert position for the node we care about.
3927 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3928 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3929 }
3930 auto *New = new (*this, alignof(PointerType)) PointerType(T, Canonical);
3931 Types.push_back(New);
3932 PointerTypes.InsertNode(New, InsertPos);
3933 return QualType(New, 0);
3934}
3935
3937 llvm::FoldingSetNodeID ID;
3938 AdjustedType::Profile(ID, Orig, New);
3939 void *InsertPos = nullptr;
3940 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3941 if (AT)
3942 return QualType(AT, 0);
3943
3944 QualType Canonical = getCanonicalType(New);
3945
3946 // Get the new insert position for the node we care about.
3947 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3948 assert(!AT && "Shouldn't be in the map!");
3949
3950 AT = new (*this, alignof(AdjustedType))
3951 AdjustedType(Type::Adjusted, Orig, New, Canonical);
3952 Types.push_back(AT);
3953 AdjustedTypes.InsertNode(AT, InsertPos);
3954 return QualType(AT, 0);
3955}
3956
3958 llvm::FoldingSetNodeID ID;
3959 AdjustedType::Profile(ID, Orig, Decayed);
3960 void *InsertPos = nullptr;
3961 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3962 if (AT)
3963 return QualType(AT, 0);
3964
3965 QualType Canonical = getCanonicalType(Decayed);
3966
3967 // Get the new insert position for the node we care about.
3968 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3969 assert(!AT && "Shouldn't be in the map!");
3970
3971 AT = new (*this, alignof(DecayedType)) DecayedType(Orig, Decayed, Canonical);
3972 Types.push_back(AT);
3973 AdjustedTypes.InsertNode(AT, InsertPos);
3974 return QualType(AT, 0);
3975}
3976
3978 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
3979
3980 QualType Decayed;
3981
3982 // C99 6.7.5.3p7:
3983 // A declaration of a parameter as "array of type" shall be
3984 // adjusted to "qualified pointer to type", where the type
3985 // qualifiers (if any) are those specified within the [ and ] of
3986 // the array type derivation.
3987 if (T->isArrayType())
3988 Decayed = getArrayDecayedType(T);
3989
3990 // C99 6.7.5.3p8:
3991 // A declaration of a parameter as "function returning type"
3992 // shall be adjusted to "pointer to function returning type", as
3993 // in 6.3.2.1.
3994 if (T->isFunctionType())
3995 Decayed = getPointerType(T);
3996
3997 return getDecayedType(T, Decayed);
3998}
3999
4001 if (Ty->isArrayParameterType())
4002 return Ty;
4003 assert(Ty->isConstantArrayType() && "Ty must be an array type.");
4004 QualType DTy = Ty.getDesugaredType(*this);
4005 const auto *ATy = cast<ConstantArrayType>(DTy);
4006 llvm::FoldingSetNodeID ID;
4007 ATy->Profile(ID, *this, ATy->getElementType(), ATy->getZExtSize(),
4008 ATy->getSizeExpr(), ATy->getSizeModifier(),
4009 ATy->getIndexTypeQualifiers().getAsOpaqueValue());
4010 void *InsertPos = nullptr;
4011 ArrayParameterType *AT =
4012 ArrayParameterTypes.FindNodeOrInsertPos(ID, InsertPos);
4013 if (AT)
4014 return QualType(AT, 0);
4015
4016 QualType Canonical;
4017 if (!DTy.isCanonical()) {
4018 Canonical = getArrayParameterType(getCanonicalType(Ty));
4019
4020 // Get the new insert position for the node we care about.
4021 AT = ArrayParameterTypes.FindNodeOrInsertPos(ID, InsertPos);
4022 assert(!AT && "Shouldn't be in the map!");
4023 }
4024
4025 AT = new (*this, alignof(ArrayParameterType))
4026 ArrayParameterType(ATy, Canonical);
4027 Types.push_back(AT);
4028 ArrayParameterTypes.InsertNode(AT, InsertPos);
4029 return QualType(AT, 0);
4030}
4031
4032/// getBlockPointerType - Return the uniqued reference to the type for
4033/// a pointer to the specified block.
4035 assert(T->isFunctionType() && "block of function types only");
4036 // Unique pointers, to guarantee there is only one block of a particular
4037 // structure.
4038 llvm::FoldingSetNodeID ID;
4040
4041 void *InsertPos = nullptr;
4042 if (BlockPointerType *PT =
4043 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4044 return QualType(PT, 0);
4045
4046 // If the block pointee type isn't canonical, this won't be a canonical
4047 // type either so fill in the canonical type field.
4048 QualType Canonical;
4049 if (!T.isCanonical()) {
4050 Canonical = getBlockPointerType(getCanonicalType(T));
4051
4052 // Get the new insert position for the node we care about.
4053 BlockPointerType *NewIP =
4054 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4055 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4056 }
4057 auto *New =
4058 new (*this, alignof(BlockPointerType)) BlockPointerType(T, Canonical);
4059 Types.push_back(New);
4060 BlockPointerTypes.InsertNode(New, InsertPos);
4061 return QualType(New, 0);
4062}
4063
4064/// getLValueReferenceType - Return the uniqued reference to the type for an
4065/// lvalue reference to the specified type.
4067ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
4068 assert((!T->isPlaceholderType() ||
4069 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
4070 "Unresolved placeholder type");
4071
4072 // Unique pointers, to guarantee there is only one pointer of a particular
4073 // structure.
4074 llvm::FoldingSetNodeID ID;
4075 ReferenceType::Profile(ID, T, SpelledAsLValue);
4076
4077 void *InsertPos = nullptr;
4078 if (LValueReferenceType *RT =
4079 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
4080 return QualType(RT, 0);
4081
4082 const auto *InnerRef = T->getAs<ReferenceType>();
4083
4084 // If the referencee type isn't canonical, this won't be a canonical type
4085 // either, so fill in the canonical type field.
4086 QualType Canonical;
4087 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
4088 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
4089 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
4090
4091 // Get the new insert position for the node we care about.
4092 LValueReferenceType *NewIP =
4093 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
4094 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4095 }
4096
4097 auto *New = new (*this, alignof(LValueReferenceType))
4098 LValueReferenceType(T, Canonical, SpelledAsLValue);
4099 Types.push_back(New);
4100 LValueReferenceTypes.InsertNode(New, InsertPos);
4101
4102 return QualType(New, 0);
4103}
4104
4105/// getRValueReferenceType - Return the uniqued reference to the type for an
4106/// rvalue reference to the specified type.
4108 assert((!T->isPlaceholderType() ||
4109 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
4110 "Unresolved placeholder type");
4111
4112 // Unique pointers, to guarantee there is only one pointer of a particular
4113 // structure.
4114 llvm::FoldingSetNodeID ID;
4115 ReferenceType::Profile(ID, T, false);
4116
4117 void *InsertPos = nullptr;
4118 if (RValueReferenceType *RT =
4119 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
4120 return QualType(RT, 0);
4121
4122 const auto *InnerRef = T->getAs<ReferenceType>();
4123
4124 // If the referencee type isn't canonical, this won't be a canonical type
4125 // either, so fill in the canonical type field.
4126 QualType Canonical;
4127 if (InnerRef || !T.isCanonical()) {
4128 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
4129 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
4130
4131 // Get the new insert position for the node we care about.
4132 RValueReferenceType *NewIP =
4133 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
4134 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4135 }
4136
4137 auto *New = new (*this, alignof(RValueReferenceType))
4138 RValueReferenceType(T, Canonical);
4139 Types.push_back(New);
4140 RValueReferenceTypes.InsertNode(New, InsertPos);
4141 return QualType(New, 0);
4142}
4143
4145 NestedNameSpecifier Qualifier,
4146 const CXXRecordDecl *Cls) const {
4147 if (!Qualifier) {
4148 assert(Cls && "At least one of Qualifier or Cls must be provided");
4149 Qualifier = NestedNameSpecifier(getCanonicalTagType(Cls).getTypePtr());
4150 } else if (!Cls) {
4151 Cls = Qualifier.getAsRecordDecl();
4152 }
4153 // Unique pointers, to guarantee there is only one pointer of a particular
4154 // structure.
4155 llvm::FoldingSetNodeID ID;
4156 MemberPointerType::Profile(ID, T, Qualifier, Cls);
4157
4158 void *InsertPos = nullptr;
4159 if (MemberPointerType *PT =
4160 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4161 return QualType(PT, 0);
4162
4163 NestedNameSpecifier CanonicalQualifier = [&] {
4164 if (!Cls)
4165 return Qualifier.getCanonical();
4166 NestedNameSpecifier R(getCanonicalTagType(Cls).getTypePtr());
4167 assert(R.isCanonical());
4168 return R;
4169 }();
4170 // If the pointee or class type isn't canonical, this won't be a canonical
4171 // type either, so fill in the canonical type field.
4172 QualType Canonical;
4173 if (!T.isCanonical() || Qualifier != CanonicalQualifier) {
4174 Canonical =
4175 getMemberPointerType(getCanonicalType(T), CanonicalQualifier, Cls);
4176 assert(!cast<MemberPointerType>(Canonical)->isSugared());
4177 // Get the new insert position for the node we care about.
4178 [[maybe_unused]] MemberPointerType *NewIP =
4179 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4180 assert(!NewIP && "Shouldn't be in the map!");
4181 }
4182 auto *New = new (*this, alignof(MemberPointerType))
4183 MemberPointerType(T, Qualifier, Canonical);
4184 Types.push_back(New);
4185 MemberPointerTypes.InsertNode(New, InsertPos);
4186 return QualType(New, 0);
4187}
4188
4189/// getConstantArrayType - Return the unique reference to the type for an
4190/// array of the specified element type.
4192 const llvm::APInt &ArySizeIn,
4193 const Expr *SizeExpr,
4195 unsigned IndexTypeQuals) const {
4196 assert((EltTy->isDependentType() ||
4197 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
4198 "Constant array of VLAs is illegal!");
4199
4200 // We only need the size as part of the type if it's instantiation-dependent.
4201 if (SizeExpr && !SizeExpr->isInstantiationDependent())
4202 SizeExpr = nullptr;
4203
4204 // Convert the array size into a canonical width matching the pointer size for
4205 // the target.
4206 llvm::APInt ArySize(ArySizeIn);
4207 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
4208
4209 llvm::FoldingSetNodeID ID;
4210 ConstantArrayType::Profile(ID, *this, EltTy, ArySize.getZExtValue(), SizeExpr,
4211 ASM, IndexTypeQuals);
4212
4213 void *InsertPos = nullptr;
4214 if (ConstantArrayType *ATP =
4215 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
4216 return QualType(ATP, 0);
4217
4218 // If the element type isn't canonical or has qualifiers, or the array bound
4219 // is instantiation-dependent, this won't be a canonical type either, so fill
4220 // in the canonical type field.
4221 QualType Canon;
4222 // FIXME: Check below should look for qualifiers behind sugar.
4223 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) {
4224 SplitQualType canonSplit = getCanonicalType(EltTy).split();
4225 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr,
4226 ASM, IndexTypeQuals);
4227 Canon = getQualifiedType(Canon, canonSplit.Quals);
4228
4229 // Get the new insert position for the node we care about.
4230 ConstantArrayType *NewIP =
4231 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
4232 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4233 }
4234
4235 auto *New = ConstantArrayType::Create(*this, EltTy, Canon, ArySize, SizeExpr,
4236 ASM, IndexTypeQuals);
4237 ConstantArrayTypes.InsertNode(New, InsertPos);
4238 Types.push_back(New);
4239 return QualType(New, 0);
4240}
4241
4242/// getVariableArrayDecayedType - Turns the given type, which may be
4243/// variably-modified, into the corresponding type with all the known
4244/// sizes replaced with [*].
4246 // Vastly most common case.
4247 if (!type->isVariablyModifiedType()) return type;
4248
4249 QualType result;
4250
4251 SplitQualType split = type.getSplitDesugaredType();
4252 const Type *ty = split.Ty;
4253 switch (ty->getTypeClass()) {
4254#define TYPE(Class, Base)
4255#define ABSTRACT_TYPE(Class, Base)
4256#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4257#include "clang/AST/TypeNodes.inc"
4258 llvm_unreachable("didn't desugar past all non-canonical types?");
4259
4260 // These types should never be variably-modified.
4261 case Type::Builtin:
4262 case Type::Complex:
4263 case Type::Vector:
4264 case Type::DependentVector:
4265 case Type::ExtVector:
4266 case Type::DependentSizedExtVector:
4267 case Type::ConstantMatrix:
4268 case Type::DependentSizedMatrix:
4269 case Type::DependentAddressSpace:
4270 case Type::ObjCObject:
4271 case Type::ObjCInterface:
4272 case Type::ObjCObjectPointer:
4273 case Type::Record:
4274 case Type::Enum:
4275 case Type::UnresolvedUsing:
4276 case Type::TypeOfExpr:
4277 case Type::TypeOf:
4278 case Type::Decltype:
4279 case Type::UnaryTransform:
4280 case Type::DependentName:
4281 case Type::InjectedClassName:
4282 case Type::TemplateSpecialization:
4283 case Type::TemplateTypeParm:
4284 case Type::SubstTemplateTypeParmPack:
4285 case Type::SubstBuiltinTemplatePack:
4286 case Type::Auto:
4287 case Type::DeducedTemplateSpecialization:
4288 case Type::PackExpansion:
4289 case Type::PackIndexing:
4290 case Type::BitInt:
4291 case Type::DependentBitInt:
4292 case Type::ArrayParameter:
4293 case Type::HLSLAttributedResource:
4294 case Type::HLSLInlineSpirv:
4295 case Type::OverflowBehavior:
4296 llvm_unreachable("type should never be variably-modified");
4297
4298 // These types can be variably-modified but should never need to
4299 // further decay.
4300 case Type::FunctionNoProto:
4301 case Type::FunctionProto:
4302 case Type::BlockPointer:
4303 case Type::MemberPointer:
4304 case Type::Pipe:
4305 return type;
4306
4307 // These types can be variably-modified. All these modifications
4308 // preserve structure except as noted by comments.
4309 // TODO: if we ever care about optimizing VLAs, there are no-op
4310 // optimizations available here.
4311 case Type::Pointer:
4314 break;
4315
4316 case Type::LValueReference: {
4317 const auto *lv = cast<LValueReferenceType>(ty);
4318 result = getLValueReferenceType(
4319 getVariableArrayDecayedType(lv->getPointeeType()),
4320 lv->isSpelledAsLValue());
4321 break;
4322 }
4323
4324 case Type::RValueReference: {
4325 const auto *lv = cast<RValueReferenceType>(ty);
4326 result = getRValueReferenceType(
4327 getVariableArrayDecayedType(lv->getPointeeType()));
4328 break;
4329 }
4330
4331 case Type::Atomic: {
4332 const auto *at = cast<AtomicType>(ty);
4333 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
4334 break;
4335 }
4336
4337 case Type::ConstantArray: {
4338 const auto *cat = cast<ConstantArrayType>(ty);
4339 result = getConstantArrayType(
4340 getVariableArrayDecayedType(cat->getElementType()),
4341 cat->getSize(),
4342 cat->getSizeExpr(),
4343 cat->getSizeModifier(),
4344 cat->getIndexTypeCVRQualifiers());
4345 break;
4346 }
4347
4348 case Type::DependentSizedArray: {
4349 const auto *dat = cast<DependentSizedArrayType>(ty);
4351 getVariableArrayDecayedType(dat->getElementType()), dat->getSizeExpr(),
4352 dat->getSizeModifier(), dat->getIndexTypeCVRQualifiers());
4353 break;
4354 }
4355
4356 // Turn incomplete types into [*] types.
4357 case Type::IncompleteArray: {
4358 const auto *iat = cast<IncompleteArrayType>(ty);
4359 result =
4361 /*size*/ nullptr, ArraySizeModifier::Normal,
4362 iat->getIndexTypeCVRQualifiers());
4363 break;
4364 }
4365
4366 // Turn VLA types into [*] types.
4367 case Type::VariableArray: {
4368 const auto *vat = cast<VariableArrayType>(ty);
4369 result =
4371 /*size*/ nullptr, ArraySizeModifier::Star,
4372 vat->getIndexTypeCVRQualifiers());
4373 break;
4374 }
4375 }
4376
4377 // Apply the top-level qualifiers from the original.
4378 return getQualifiedType(result, split.Quals);
4379}
4380
4381/// getVariableArrayType - Returns a non-unique reference to the type for a
4382/// variable array of the specified element type.
4385 unsigned IndexTypeQuals) const {
4386 // Since we don't unique expressions, it isn't possible to unique VLA's
4387 // that have an expression provided for their size.
4388 QualType Canon;
4389
4390 // Be sure to pull qualifiers off the element type.
4391 // FIXME: Check below should look for qualifiers behind sugar.
4392 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
4393 SplitQualType canonSplit = getCanonicalType(EltTy).split();
4394 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
4395 IndexTypeQuals);
4396 Canon = getQualifiedType(Canon, canonSplit.Quals);
4397 }
4398
4399 auto *New = new (*this, alignof(VariableArrayType))
4400 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals);
4401
4402 VariableArrayTypes.push_back(New);
4403 Types.push_back(New);
4404 return QualType(New, 0);
4405}
4406
4407/// getDependentSizedArrayType - Returns a non-unique reference to
4408/// the type for a dependently-sized array of the specified element
4409/// type.
4413 unsigned elementTypeQuals) const {
4414 assert((!numElements || numElements->isTypeDependent() ||
4415 numElements->isValueDependent()) &&
4416 "Size must be type- or value-dependent!");
4417
4418 SplitQualType canonElementType = getCanonicalType(elementType).split();
4419
4420 void *insertPos = nullptr;
4421 llvm::FoldingSetNodeID ID;
4423 ID, *this, numElements ? QualType(canonElementType.Ty, 0) : elementType,
4424 ASM, elementTypeQuals, numElements);
4425
4426 // Look for an existing type with these properties.
4427 DependentSizedArrayType *canonTy =
4428 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
4429
4430 // Dependently-sized array types that do not have a specified number
4431 // of elements will have their sizes deduced from a dependent
4432 // initializer.
4433 if (!numElements) {
4434 if (canonTy)
4435 return QualType(canonTy, 0);
4436
4437 auto *newType = new (*this, alignof(DependentSizedArrayType))
4438 DependentSizedArrayType(elementType, QualType(), numElements, ASM,
4439 elementTypeQuals);
4440 DependentSizedArrayTypes.InsertNode(newType, insertPos);
4441 Types.push_back(newType);
4442 return QualType(newType, 0);
4443 }
4444
4445 // If we don't have one, build one.
4446 if (!canonTy) {
4447 canonTy = new (*this, alignof(DependentSizedArrayType))
4448 DependentSizedArrayType(QualType(canonElementType.Ty, 0), QualType(),
4449 numElements, ASM, elementTypeQuals);
4450 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
4451 Types.push_back(canonTy);
4452 }
4453
4454 // Apply qualifiers from the element type to the array.
4455 QualType canon = getQualifiedType(QualType(canonTy,0),
4456 canonElementType.Quals);
4457
4458 // If we didn't need extra canonicalization for the element type or the size
4459 // expression, then just use that as our result.
4460 if (QualType(canonElementType.Ty, 0) == elementType &&
4461 canonTy->getSizeExpr() == numElements)
4462 return canon;
4463
4464 // Otherwise, we need to build a type which follows the spelling
4465 // of the element type.
4466 auto *sugaredType = new (*this, alignof(DependentSizedArrayType))
4467 DependentSizedArrayType(elementType, canon, numElements, ASM,
4468 elementTypeQuals);
4469 Types.push_back(sugaredType);
4470 return QualType(sugaredType, 0);
4471}
4472
4475 unsigned elementTypeQuals) const {
4476 llvm::FoldingSetNodeID ID;
4477 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
4478
4479 void *insertPos = nullptr;
4480 if (IncompleteArrayType *iat =
4481 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
4482 return QualType(iat, 0);
4483
4484 // If the element type isn't canonical, this won't be a canonical type
4485 // either, so fill in the canonical type field. We also have to pull
4486 // qualifiers off the element type.
4487 QualType canon;
4488
4489 // FIXME: Check below should look for qualifiers behind sugar.
4490 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
4491 SplitQualType canonSplit = getCanonicalType(elementType).split();
4492 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
4493 ASM, elementTypeQuals);
4494 canon = getQualifiedType(canon, canonSplit.Quals);
4495
4496 // Get the new insert position for the node we care about.
4497 IncompleteArrayType *existing =
4498 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
4499 assert(!existing && "Shouldn't be in the map!"); (void) existing;
4500 }
4501
4502 auto *newType = new (*this, alignof(IncompleteArrayType))
4503 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
4504
4505 IncompleteArrayTypes.InsertNode(newType, insertPos);
4506 Types.push_back(newType);
4507 return QualType(newType, 0);
4508}
4509
4512#define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS) \
4513 {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount::getScalable(ELTS), \
4514 NUMVECTORS};
4515
4516#define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS) \
4517 {ELTTY, llvm::ElementCount::getScalable(ELTS), NUMVECTORS};
4518
4519 switch (Ty->getKind()) {
4520 default:
4521 llvm_unreachable("Unsupported builtin vector type");
4522
4523#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4524 ElBits, NF, IsSigned) \
4525 case BuiltinType::Id: \
4526 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4527 llvm::ElementCount::getScalable(NumEls), NF};
4528#define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4529 ElBits, NF) \
4530 case BuiltinType::Id: \
4531 return {ElBits == 16 ? HalfTy : (ElBits == 32 ? FloatTy : DoubleTy), \
4532 llvm::ElementCount::getScalable(NumEls), NF};
4533#define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4534 ElBits, NF) \
4535 case BuiltinType::Id: \
4536 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4537#define SVE_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4538 ElBits, NF) \
4539 case BuiltinType::Id: \
4540 return {MFloat8Ty, llvm::ElementCount::getScalable(NumEls), NF};
4541#define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4542 case BuiltinType::Id: \
4543 return {BoolTy, llvm::ElementCount::getScalable(NumEls), NF};
4544#include "clang/Basic/AArch64ACLETypes.def"
4545
4546#define RVV_VECTOR_TYPE_INT(Name, Id, SingletonId, NumEls, ElBits, NF, \
4547 IsSigned) \
4548 case BuiltinType::Id: \
4549 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4550 llvm::ElementCount::getScalable(NumEls), NF};
4551#define RVV_VECTOR_TYPE_FLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4552 case BuiltinType::Id: \
4553 return {ElBits == 16 ? Float16Ty : (ElBits == 32 ? FloatTy : DoubleTy), \
4554 llvm::ElementCount::getScalable(NumEls), NF};
4555#define RVV_VECTOR_TYPE_BFLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4556 case BuiltinType::Id: \
4557 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4558#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4559 case BuiltinType::Id: \
4560 return {BoolTy, llvm::ElementCount::getScalable(NumEls), 1};
4561#include "clang/Basic/RISCVVTypes.def"
4562 }
4563}
4564
4565/// getExternrefType - Return a WebAssembly externref type, which represents an
4566/// opaque reference to a host value.
4568 if (Target->getTriple().isWasm() && Target->hasFeature("reference-types")) {
4569#define WASM_REF_TYPE(Name, MangledName, Id, SingletonId, AS) \
4570 if (BuiltinType::Id == BuiltinType::WasmExternRef) \
4571 return SingletonId;
4572#include "clang/Basic/WebAssemblyReferenceTypes.def"
4573 }
4574 llvm_unreachable(
4575 "shouldn't try to generate type externref outside WebAssembly target");
4576}
4577
4578/// getScalableVectorType - Return the unique reference to a scalable vector
4579/// type of the specified element type and size. VectorType must be a built-in
4580/// type.
4582 unsigned NumFields) const {
4583 auto K = llvm::ScalableVecTyKey{EltTy, NumElts, NumFields};
4584 if (auto It = ScalableVecTyMap.find(K); It != ScalableVecTyMap.end())
4585 return It->second;
4586
4587 if (Target->hasAArch64ACLETypes()) {
4588 uint64_t EltTySize = getTypeSize(EltTy);
4589
4590#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4591 ElBits, NF, IsSigned) \
4592 if (EltTy->hasIntegerRepresentation() && !EltTy->isBooleanType() && \
4593 EltTy->hasSignedIntegerRepresentation() == IsSigned && \
4594 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4595 return ScalableVecTyMap[K] = SingletonId; \
4596 }
4597#define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4598 ElBits, NF) \
4599 if (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4600 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4601 return ScalableVecTyMap[K] = SingletonId; \
4602 }
4603#define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4604 ElBits, NF) \
4605 if (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4606 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4607 return ScalableVecTyMap[K] = SingletonId; \
4608 }
4609#define SVE_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4610 ElBits, NF) \
4611 if (EltTy->isMFloat8Type() && EltTySize == ElBits && \
4612 NumElts == (NumEls * NF) && NumFields == 1) { \
4613 return ScalableVecTyMap[K] = SingletonId; \
4614 }
4615#define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4616 if (EltTy->isBooleanType() && NumElts == (NumEls * NF) && NumFields == 1) \
4617 return ScalableVecTyMap[K] = SingletonId;
4618#include "clang/Basic/AArch64ACLETypes.def"
4619 } else if (Target->hasRISCVVTypes()) {
4620 uint64_t EltTySize = getTypeSize(EltTy);
4621#define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned, \
4622 IsFP, IsBF) \
4623 if (!EltTy->isBooleanType() && \
4624 ((EltTy->hasIntegerRepresentation() && \
4625 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \
4626 (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4627 IsFP && !IsBF) || \
4628 (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4629 IsBF && !IsFP)) && \
4630 EltTySize == ElBits && NumElts == NumEls && NumFields == NF) \
4631 return ScalableVecTyMap[K] = SingletonId;
4632#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4633 if (EltTy->isBooleanType() && NumElts == NumEls) \
4634 return ScalableVecTyMap[K] = SingletonId;
4635#include "clang/Basic/RISCVVTypes.def"
4636 }
4637 return QualType();
4638}
4639
4640/// getVectorType - Return the unique reference to a vector type of
4641/// the specified element type and size. VectorType must be a built-in type.
4643 VectorKind VecKind) const {
4644 assert(vecType->isBuiltinType() ||
4645 (vecType->isBitIntType() &&
4646 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4647 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits())));
4648
4649 // Check if we've already instantiated a vector of this type.
4650 llvm::FoldingSetNodeID ID;
4651 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
4652
4653 void *InsertPos = nullptr;
4654 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4655 return QualType(VTP, 0);
4656
4657 // If the element type isn't canonical, this won't be a canonical type either,
4658 // so fill in the canonical type field.
4659 QualType Canonical;
4660 if (!vecType.isCanonical()) {
4661 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
4662
4663 // Get the new insert position for the node we care about.
4664 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4665 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4666 }
4667 auto *New = new (*this, alignof(VectorType))
4668 VectorType(vecType, NumElts, Canonical, VecKind);
4669 VectorTypes.InsertNode(New, InsertPos);
4670 Types.push_back(New);
4671 return QualType(New, 0);
4672}
4673
4675 SourceLocation AttrLoc,
4676 VectorKind VecKind) const {
4677 llvm::FoldingSetNodeID ID;
4678 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
4679 VecKind);
4680 void *InsertPos = nullptr;
4681 DependentVectorType *Canon =
4682 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4684
4685 if (Canon) {
4686 New = new (*this, alignof(DependentVectorType)) DependentVectorType(
4687 VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
4688 } else {
4689 QualType CanonVecTy = getCanonicalType(VecType);
4690 if (CanonVecTy == VecType) {
4691 New = new (*this, alignof(DependentVectorType))
4692 DependentVectorType(VecType, QualType(), SizeExpr, AttrLoc, VecKind);
4693
4694 DependentVectorType *CanonCheck =
4695 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4696 assert(!CanonCheck &&
4697 "Dependent-sized vector_size canonical type broken");
4698 (void)CanonCheck;
4699 DependentVectorTypes.InsertNode(New, InsertPos);
4700 } else {
4701 QualType CanonTy = getDependentVectorType(CanonVecTy, SizeExpr,
4702 SourceLocation(), VecKind);
4703 New = new (*this, alignof(DependentVectorType))
4704 DependentVectorType(VecType, CanonTy, SizeExpr, AttrLoc, VecKind);
4705 }
4706 }
4707
4708 Types.push_back(New);
4709 return QualType(New, 0);
4710}
4711
4712/// getExtVectorType - Return the unique reference to an extended vector type of
4713/// the specified element type and size. VectorType must be a built-in type.
4715 unsigned NumElts) const {
4716 assert(vecType->isBuiltinType() || vecType->isDependentType() ||
4717 (vecType->isBitIntType() &&
4718 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4719 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits())));
4720
4721 // Check if we've already instantiated a vector of this type.
4722 llvm::FoldingSetNodeID ID;
4723 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
4725 void *InsertPos = nullptr;
4726 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4727 return QualType(VTP, 0);
4728
4729 // If the element type isn't canonical, this won't be a canonical type either,
4730 // so fill in the canonical type field.
4731 QualType Canonical;
4732 if (!vecType.isCanonical()) {
4733 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
4734
4735 // Get the new insert position for the node we care about.
4736 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4737 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4738 }
4739 auto *New = new (*this, alignof(ExtVectorType))
4740 ExtVectorType(vecType, NumElts, Canonical);
4741 VectorTypes.InsertNode(New, InsertPos);
4742 Types.push_back(New);
4743 return QualType(New, 0);
4744}
4745
4748 Expr *SizeExpr,
4749 SourceLocation AttrLoc) const {
4750 llvm::FoldingSetNodeID ID;
4752 SizeExpr);
4753
4754 void *InsertPos = nullptr;
4756 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4758 if (Canon) {
4759 // We already have a canonical version of this array type; use it as
4760 // the canonical type for a newly-built type.
4761 New = new (*this, alignof(DependentSizedExtVectorType))
4762 DependentSizedExtVectorType(vecType, QualType(Canon, 0), SizeExpr,
4763 AttrLoc);
4764 } else {
4765 QualType CanonVecTy = getCanonicalType(vecType);
4766 if (CanonVecTy == vecType) {
4767 New = new (*this, alignof(DependentSizedExtVectorType))
4768 DependentSizedExtVectorType(vecType, QualType(), SizeExpr, AttrLoc);
4769
4770 DependentSizedExtVectorType *CanonCheck
4771 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4772 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
4773 (void)CanonCheck;
4774 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
4775 } else {
4776 QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
4777 SourceLocation());
4778 New = new (*this, alignof(DependentSizedExtVectorType))
4779 DependentSizedExtVectorType(vecType, CanonExtTy, SizeExpr, AttrLoc);
4780 }
4781 }
4782
4783 Types.push_back(New);
4784 return QualType(New, 0);
4785}
4786
4788 unsigned NumColumns) const {
4789 llvm::FoldingSetNodeID ID;
4790 ConstantMatrixType::Profile(ID, ElementTy, NumRows, NumColumns,
4791 Type::ConstantMatrix);
4792
4793 assert(MatrixType::isValidElementType(ElementTy, getLangOpts()) &&
4794 "need a valid element type");
4795 assert(NumRows > 0 && NumRows <= LangOpts.MaxMatrixDimension &&
4796 NumColumns > 0 && NumColumns <= LangOpts.MaxMatrixDimension &&
4797 "need valid matrix dimensions");
4798 void *InsertPos = nullptr;
4799 if (ConstantMatrixType *MTP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos))
4800 return QualType(MTP, 0);
4801
4802 QualType Canonical;
4803 if (!ElementTy.isCanonical()) {
4804 Canonical =
4805 getConstantMatrixType(getCanonicalType(ElementTy), NumRows, NumColumns);
4806
4807 ConstantMatrixType *NewIP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4808 assert(!NewIP && "Matrix type shouldn't already exist in the map");
4809 (void)NewIP;
4810 }
4811
4812 auto *New = new (*this, alignof(ConstantMatrixType))
4813 ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical);
4814 MatrixTypes.InsertNode(New, InsertPos);
4815 Types.push_back(New);
4816 return QualType(New, 0);
4817}
4818
4820 Expr *RowExpr,
4821 Expr *ColumnExpr,
4822 SourceLocation AttrLoc) const {
4823 QualType CanonElementTy = getCanonicalType(ElementTy);
4824 llvm::FoldingSetNodeID ID;
4825 DependentSizedMatrixType::Profile(ID, *this, CanonElementTy, RowExpr,
4826 ColumnExpr);
4827
4828 void *InsertPos = nullptr;
4830 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4831
4832 if (!Canon) {
4833 Canon = new (*this, alignof(DependentSizedMatrixType))
4834 DependentSizedMatrixType(CanonElementTy, QualType(), RowExpr,
4835 ColumnExpr, AttrLoc);
4836#ifndef NDEBUG
4837 DependentSizedMatrixType *CanonCheck =
4838 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4839 assert(!CanonCheck && "Dependent-sized matrix canonical type broken");
4840#endif
4841 DependentSizedMatrixTypes.InsertNode(Canon, InsertPos);
4842 Types.push_back(Canon);
4843 }
4844
4845 // Already have a canonical version of the matrix type
4846 //
4847 // If it exactly matches the requested type, use it directly.
4848 if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr &&
4849 Canon->getRowExpr() == ColumnExpr)
4850 return QualType(Canon, 0);
4851
4852 // Use Canon as the canonical type for newly-built type.
4854 DependentSizedMatrixType(ElementTy, QualType(Canon, 0), RowExpr,
4855 ColumnExpr, AttrLoc);
4856 Types.push_back(New);
4857 return QualType(New, 0);
4858}
4859
4861 Expr *AddrSpaceExpr,
4862 SourceLocation AttrLoc) const {
4863 assert(AddrSpaceExpr->isInstantiationDependent());
4864
4865 QualType canonPointeeType = getCanonicalType(PointeeType);
4866
4867 void *insertPos = nullptr;
4868 llvm::FoldingSetNodeID ID;
4869 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
4870 AddrSpaceExpr);
4871
4872 DependentAddressSpaceType *canonTy =
4873 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
4874
4875 if (!canonTy) {
4876 canonTy = new (*this, alignof(DependentAddressSpaceType))
4877 DependentAddressSpaceType(canonPointeeType, QualType(), AddrSpaceExpr,
4878 AttrLoc);
4879 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
4880 Types.push_back(canonTy);
4881 }
4882
4883 if (canonPointeeType == PointeeType &&
4884 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
4885 return QualType(canonTy, 0);
4886
4887 auto *sugaredType = new (*this, alignof(DependentAddressSpaceType))
4888 DependentAddressSpaceType(PointeeType, QualType(canonTy, 0),
4889 AddrSpaceExpr, AttrLoc);
4890 Types.push_back(sugaredType);
4891 return QualType(sugaredType, 0);
4892}
4893
4894/// Determine whether \p T is canonical as the result type of a function.
4896 return T.isCanonical() &&
4897 (T.getObjCLifetime() == Qualifiers::OCL_None ||
4898 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
4899}
4900
4901/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
4902QualType
4904 const FunctionType::ExtInfo &Info) const {
4905 // FIXME: This assertion cannot be enabled (yet) because the ObjC rewriter
4906 // functionality creates a function without a prototype regardless of
4907 // language mode (so it makes them even in C++). Once the rewriter has been
4908 // fixed, this assertion can be enabled again.
4909 //assert(!LangOpts.requiresStrictPrototypes() &&
4910 // "strict prototypes are disabled");
4911
4912 // Unique functions, to guarantee there is only one function of a particular
4913 // structure.
4914 llvm::FoldingSetNodeID ID;
4915 FunctionNoProtoType::Profile(ID, ResultTy, Info);
4916
4917 void *InsertPos = nullptr;
4918 if (FunctionNoProtoType *FT =
4919 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
4920 return QualType(FT, 0);
4921
4922 QualType Canonical;
4923 if (!isCanonicalResultType(ResultTy)) {
4924 Canonical =
4926
4927 // Get the new insert position for the node we care about.
4928 FunctionNoProtoType *NewIP =
4929 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
4930 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4931 }
4932
4933 auto *New = new (*this, alignof(FunctionNoProtoType))
4934 FunctionNoProtoType(ResultTy, Canonical, Info);
4935 Types.push_back(New);
4936 FunctionNoProtoTypes.InsertNode(New, InsertPos);
4937 return QualType(New, 0);
4938}
4939
4942 CanQualType CanResultType = getCanonicalType(ResultType);
4943
4944 // Canonical result types do not have ARC lifetime qualifiers.
4945 if (CanResultType.getQualifiers().hasObjCLifetime()) {
4946 Qualifiers Qs = CanResultType.getQualifiers();
4947 Qs.removeObjCLifetime();
4949 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
4950 }
4951
4952 return CanResultType;
4953}
4954
4956 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
4957 if (ESI.Type == EST_None)
4958 return true;
4959 if (!NoexceptInType)
4960 return false;
4961
4962 // C++17 onwards: exception specification is part of the type, as a simple
4963 // boolean "can this function type throw".
4964 if (ESI.Type == EST_BasicNoexcept)
4965 return true;
4966
4967 // A noexcept(expr) specification is (possibly) canonical if expr is
4968 // value-dependent.
4969 if (ESI.Type == EST_DependentNoexcept)
4970 return true;
4971
4972 // A dynamic exception specification is canonical if it only contains pack
4973 // expansions (so we can't tell whether it's non-throwing) and all its
4974 // contained types are canonical.
4975 if (ESI.Type == EST_Dynamic) {
4976 bool AnyPackExpansions = false;
4977 for (QualType ET : ESI.Exceptions) {
4978 if (!ET.isCanonical())
4979 return false;
4980 if (ET->getAs<PackExpansionType>())
4981 AnyPackExpansions = true;
4982 }
4983 return AnyPackExpansions;
4984 }
4985
4986 return false;
4987}
4988
4989QualType ASTContext::getFunctionTypeInternal(
4990 QualType ResultTy, ArrayRef<QualType> ArgArray,
4991 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
4992 size_t NumArgs = ArgArray.size();
4993
4994 // Unique functions, to guarantee there is only one function of a particular
4995 // structure.
4996 llvm::FoldingSetNodeID ID;
4997 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
4998 *this, true);
4999
5000 QualType Canonical;
5001 bool Unique = false;
5002
5003 void *InsertPos = nullptr;
5004 if (FunctionProtoType *FPT =
5005 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
5006 QualType Existing = QualType(FPT, 0);
5007
5008 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
5009 // it so long as our exception specification doesn't contain a dependent
5010 // noexcept expression, or we're just looking for a canonical type.
5011 // Otherwise, we're going to need to create a type
5012 // sugar node to hold the concrete expression.
5013 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
5014 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
5015 return Existing;
5016
5017 // We need a new type sugar node for this one, to hold the new noexcept
5018 // expression. We do no canonicalization here, but that's OK since we don't
5019 // expect to see the same noexcept expression much more than once.
5020 Canonical = getCanonicalType(Existing);
5021 Unique = true;
5022 }
5023
5024 bool NoexceptInType = getLangOpts().CPlusPlus17;
5025 bool IsCanonicalExceptionSpec =
5027
5028 // Determine whether the type being created is already canonical or not.
5029 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
5030 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
5031 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
5032 if (!ArgArray[i].isCanonicalAsParam())
5033 isCanonical = false;
5034
5035 if (OnlyWantCanonical)
5036 assert(isCanonical &&
5037 "given non-canonical parameters constructing canonical type");
5038
5039 // If this type isn't canonical, get the canonical version of it if we don't
5040 // already have it. The exception spec is only partially part of the
5041 // canonical type, and only in C++17 onwards.
5042 if (!isCanonical && Canonical.isNull()) {
5043 SmallVector<QualType, 16> CanonicalArgs;
5044 CanonicalArgs.reserve(NumArgs);
5045 for (unsigned i = 0; i != NumArgs; ++i)
5046 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
5047
5048 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
5049 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
5050 CanonicalEPI.HasTrailingReturn = false;
5051
5052 if (IsCanonicalExceptionSpec) {
5053 // Exception spec is already OK.
5054 } else if (NoexceptInType) {
5055 switch (EPI.ExceptionSpec.Type) {
5057 // We don't know yet. It shouldn't matter what we pick here; no-one
5058 // should ever look at this.
5059 [[fallthrough]];
5060 case EST_None: case EST_MSAny: case EST_NoexceptFalse:
5061 CanonicalEPI.ExceptionSpec.Type = EST_None;
5062 break;
5063
5064 // A dynamic exception specification is almost always "not noexcept",
5065 // with the exception that a pack expansion might expand to no types.
5066 case EST_Dynamic: {
5067 bool AnyPacks = false;
5068 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
5069 if (ET->getAs<PackExpansionType>())
5070 AnyPacks = true;
5071 ExceptionTypeStorage.push_back(getCanonicalType(ET));
5072 }
5073 if (!AnyPacks)
5074 CanonicalEPI.ExceptionSpec.Type = EST_None;
5075 else {
5076 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
5077 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
5078 }
5079 break;
5080 }
5081
5082 case EST_DynamicNone:
5083 case EST_BasicNoexcept:
5084 case EST_NoexceptTrue:
5085 case EST_NoThrow:
5086 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
5087 break;
5088
5090 llvm_unreachable("dependent noexcept is already canonical");
5091 }
5092 } else {
5093 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
5094 }
5095
5096 // Adjust the canonical function result type.
5097 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
5098 Canonical =
5099 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
5100
5101 // Get the new insert position for the node we care about.
5102 FunctionProtoType *NewIP =
5103 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
5104 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
5105 }
5106
5107 // Compute the needed size to hold this FunctionProtoType and the
5108 // various trailing objects.
5109 auto ESH = FunctionProtoType::getExceptionSpecSize(
5110 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
5111 size_t Size = FunctionProtoType::totalSizeToAlloc<
5112 QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields,
5113 FunctionType::FunctionTypeExtraAttributeInfo,
5114 FunctionType::FunctionTypeArmAttributes, FunctionType::ExceptionType,
5115 Expr *, FunctionDecl *, FunctionProtoType::ExtParameterInfo, Qualifiers,
5116 FunctionEffect, EffectConditionExpr>(
5119 EPI.requiresFunctionProtoTypeArmAttributes(), ESH.NumExceptionType,
5120 ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
5121 EPI.ExtParameterInfos ? NumArgs : 0,
5123 EPI.FunctionEffects.conditions().size());
5124
5125 auto *FTP = (FunctionProtoType *)Allocate(Size, alignof(FunctionProtoType));
5126 FunctionProtoType::ExtProtoInfo newEPI = EPI;
5127 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
5128 Types.push_back(FTP);
5129 if (!Unique)
5130 FunctionProtoTypes.InsertNode(FTP, InsertPos);
5131 if (!EPI.FunctionEffects.empty())
5132 AnyFunctionEffects = true;
5133 return QualType(FTP, 0);
5134}
5135
5136QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
5137 llvm::FoldingSetNodeID ID;
5138 PipeType::Profile(ID, T, ReadOnly);
5139
5140 void *InsertPos = nullptr;
5141 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
5142 return QualType(PT, 0);
5143
5144 // If the pipe element type isn't canonical, this won't be a canonical type
5145 // either, so fill in the canonical type field.
5146 QualType Canonical;
5147 if (!T.isCanonical()) {
5148 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
5149
5150 // Get the new insert position for the node we care about.
5151 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
5152 assert(!NewIP && "Shouldn't be in the map!");
5153 (void)NewIP;
5154 }
5155 auto *New = new (*this, alignof(PipeType)) PipeType(T, Canonical, ReadOnly);
5156 Types.push_back(New);
5157 PipeTypes.InsertNode(New, InsertPos);
5158 return QualType(New, 0);
5159}
5160
5162 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
5163 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
5164 : Ty;
5165}
5166
5168 return getPipeType(T, true);
5169}
5170
5172 return getPipeType(T, false);
5173}
5174
5175QualType ASTContext::getBitIntType(bool IsUnsigned, unsigned NumBits) const {
5176 llvm::FoldingSetNodeID ID;
5177 BitIntType::Profile(ID, IsUnsigned, NumBits);
5178
5179 void *InsertPos = nullptr;
5180 if (BitIntType *EIT = BitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
5181 return QualType(EIT, 0);
5182
5183 auto *New = new (*this, alignof(BitIntType)) BitIntType(IsUnsigned, NumBits);
5184 BitIntTypes.InsertNode(New, InsertPos);
5185 Types.push_back(New);
5186 return QualType(New, 0);
5187}
5188
5190 Expr *NumBitsExpr) const {
5191 assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent");
5192 llvm::FoldingSetNodeID ID;
5193 DependentBitIntType::Profile(ID, *this, IsUnsigned, NumBitsExpr);
5194
5195 void *InsertPos = nullptr;
5196 if (DependentBitIntType *Existing =
5197 DependentBitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
5198 return QualType(Existing, 0);
5199
5200 auto *New = new (*this, alignof(DependentBitIntType))
5201 DependentBitIntType(IsUnsigned, NumBitsExpr);
5202 DependentBitIntTypes.InsertNode(New, InsertPos);
5203
5204 Types.push_back(New);
5205 return QualType(New, 0);
5206}
5207
5210 using Kind = PredefinedSugarType::Kind;
5211
5212 if (auto *Target = PredefinedSugarTypes[llvm::to_underlying(KD)];
5213 Target != nullptr)
5214 return QualType(Target, 0);
5215
5216 auto getCanonicalType = [](const ASTContext &Ctx, Kind KDI) -> QualType {
5217 switch (KDI) {
5218 // size_t (C99TC3 6.5.3.4), signed size_t (C++23 5.13.2) and
5219 // ptrdiff_t (C99TC3 6.5.6) Although these types are not built-in, they
5220 // are part of the core language and are widely used. Using
5221 // PredefinedSugarType makes these types as named sugar types rather than
5222 // standard integer types, enabling better hints and diagnostics.
5223 case Kind::SizeT:
5224 return Ctx.getFromTargetType(Ctx.Target->getSizeType());
5225 case Kind::SignedSizeT:
5226 return Ctx.getFromTargetType(Ctx.Target->getSignedSizeType());
5227 case Kind::PtrdiffT:
5228 return Ctx.getFromTargetType(Ctx.Target->getPtrDiffType(LangAS::Default));
5229 }
5230 llvm_unreachable("unexpected kind");
5231 };
5232 auto *New = new (*this, alignof(PredefinedSugarType))
5233 PredefinedSugarType(KD, &Idents.get(PredefinedSugarType::getName(KD)),
5234 getCanonicalType(*this, static_cast<Kind>(KD)));
5235 Types.push_back(New);
5236 PredefinedSugarTypes[llvm::to_underlying(KD)] = New;
5237 return QualType(New, 0);
5238}
5239
5241 NestedNameSpecifier Qualifier,
5242 const TypeDecl *Decl) const {
5243 if (auto *Tag = dyn_cast<TagDecl>(Decl))
5244 return getTagType(Keyword, Qualifier, Tag,
5245 /*OwnsTag=*/false);
5246 if (auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
5247 return getTypedefType(Keyword, Qualifier, Typedef);
5248 if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(Decl))
5249 return getUnresolvedUsingType(Keyword, Qualifier, UD);
5250
5252 assert(!Qualifier);
5253 return QualType(Decl->TypeForDecl, 0);
5254}
5255
5257 if (auto *Tag = dyn_cast<TagDecl>(TD))
5258 return getCanonicalTagType(Tag);
5259 if (auto *TN = dyn_cast<TypedefNameDecl>(TD))
5260 return getCanonicalType(TN->getUnderlyingType());
5261 if (const auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(TD))
5263 assert(TD->TypeForDecl);
5264 return TD->TypeForDecl->getCanonicalTypeUnqualified();
5265}
5266
5268 if (const auto *TD = dyn_cast<TagDecl>(Decl))
5269 return getCanonicalTagType(TD);
5270 if (const auto *TD = dyn_cast<TypedefNameDecl>(Decl);
5271 isa_and_nonnull<TypedefDecl, TypeAliasDecl>(TD))
5273 /*Qualifier=*/std::nullopt, TD);
5274 if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl))
5275 return getCanonicalUnresolvedUsingType(Using);
5276
5277 assert(Decl->TypeForDecl);
5278 return QualType(Decl->TypeForDecl, 0);
5279}
5280
5281/// getTypedefType - Return the unique reference to the type for the
5282/// specified typedef name decl.
5285 NestedNameSpecifier Qualifier,
5286 const TypedefNameDecl *Decl, QualType UnderlyingType,
5287 std::optional<bool> TypeMatchesDeclOrNone) const {
5288 if (!TypeMatchesDeclOrNone) {
5289 QualType DeclUnderlyingType = Decl->getUnderlyingType();
5290 assert(!DeclUnderlyingType.isNull());
5291 if (UnderlyingType.isNull())
5292 UnderlyingType = DeclUnderlyingType;
5293 else
5294 assert(hasSameType(UnderlyingType, DeclUnderlyingType));
5295 TypeMatchesDeclOrNone = UnderlyingType == DeclUnderlyingType;
5296 } else {
5297 // FIXME: This is a workaround for a serialization cycle: assume the decl
5298 // underlying type is not available; don't touch it.
5299 assert(!UnderlyingType.isNull());
5300 }
5301
5302 if (Keyword == ElaboratedTypeKeyword::None && !Qualifier &&
5303 *TypeMatchesDeclOrNone) {
5304 if (Decl->TypeForDecl)
5305 return QualType(Decl->TypeForDecl, 0);
5306
5307 auto *NewType = new (*this, alignof(TypedefType))
5308 TypedefType(Type::Typedef, Keyword, Qualifier, Decl, UnderlyingType,
5309 !*TypeMatchesDeclOrNone);
5310
5311 Types.push_back(NewType);
5312 Decl->TypeForDecl = NewType;
5313 return QualType(NewType, 0);
5314 }
5315
5316 llvm::FoldingSetNodeID ID;
5317 TypedefType::Profile(ID, Keyword, Qualifier, Decl,
5318 *TypeMatchesDeclOrNone ? QualType() : UnderlyingType);
5319
5320 void *InsertPos = nullptr;
5321 if (FoldingSetPlaceholder<TypedefType> *Placeholder =
5322 TypedefTypes.FindNodeOrInsertPos(ID, InsertPos))
5323 return QualType(Placeholder->getType(), 0);
5324
5325 void *Mem =
5326 Allocate(TypedefType::totalSizeToAlloc<FoldingSetPlaceholder<TypedefType>,
5328 1, !!Qualifier, !*TypeMatchesDeclOrNone),
5329 alignof(TypedefType));
5330 auto *NewType =
5331 new (Mem) TypedefType(Type::Typedef, Keyword, Qualifier, Decl,
5332 UnderlyingType, !*TypeMatchesDeclOrNone);
5333 auto *Placeholder = new (NewType->getFoldingSetPlaceholder())
5335 TypedefTypes.InsertNode(Placeholder, InsertPos);
5336 Types.push_back(NewType);
5337 return QualType(NewType, 0);
5338}
5339
5341 NestedNameSpecifier Qualifier,
5342 const UsingShadowDecl *D,
5343 QualType UnderlyingType) const {
5344 // FIXME: This is expensive to compute every time!
5345 if (UnderlyingType.isNull()) {
5346 const auto *UD = cast<UsingDecl>(D->getIntroducer());
5347 UnderlyingType =
5350 UD->getQualifier(), cast<TypeDecl>(D->getTargetDecl()));
5351 }
5352
5353 llvm::FoldingSetNodeID ID;
5354 UsingType::Profile(ID, Keyword, Qualifier, D, UnderlyingType);
5355
5356 void *InsertPos = nullptr;
5357 if (const UsingType *T = UsingTypes.FindNodeOrInsertPos(ID, InsertPos))
5358 return QualType(T, 0);
5359
5360 assert(!UnderlyingType.hasLocalQualifiers());
5361
5362 assert(
5364 UnderlyingType));
5365
5366 void *Mem =
5367 Allocate(UsingType::totalSizeToAlloc<NestedNameSpecifier>(!!Qualifier),
5368 alignof(UsingType));
5369 UsingType *T = new (Mem) UsingType(Keyword, Qualifier, D, UnderlyingType);
5370 Types.push_back(T);
5371 UsingTypes.InsertNode(T, InsertPos);
5372 return QualType(T, 0);
5373}
5374
5375TagType *ASTContext::getTagTypeInternal(ElaboratedTypeKeyword Keyword,
5376 NestedNameSpecifier Qualifier,
5377 const TagDecl *TD, bool OwnsTag,
5378 bool IsInjected,
5379 const Type *CanonicalType,
5380 bool WithFoldingSetNode) const {
5381 auto [TC, Size] = [&] {
5382 switch (TD->getDeclKind()) {
5383 case Decl::Enum:
5384 static_assert(alignof(EnumType) == alignof(TagType));
5385 return std::make_tuple(Type::Enum, sizeof(EnumType));
5386 case Decl::ClassTemplatePartialSpecialization:
5387 case Decl::ClassTemplateSpecialization:
5388 case Decl::CXXRecord:
5389 static_assert(alignof(RecordType) == alignof(TagType));
5390 static_assert(alignof(InjectedClassNameType) == alignof(TagType));
5391 if (cast<CXXRecordDecl>(TD)->hasInjectedClassType())
5392 return std::make_tuple(Type::InjectedClassName,
5393 sizeof(InjectedClassNameType));
5394 [[fallthrough]];
5395 case Decl::Record:
5396 return std::make_tuple(Type::Record, sizeof(RecordType));
5397 default:
5398 llvm_unreachable("unexpected decl kind");
5399 }
5400 }();
5401
5402 if (Qualifier) {
5403 static_assert(alignof(NestedNameSpecifier) <= alignof(TagType));
5404 Size = llvm::alignTo(Size, alignof(NestedNameSpecifier)) +
5405 sizeof(NestedNameSpecifier);
5406 }
5407 void *Mem;
5408 if (WithFoldingSetNode) {
5409 // FIXME: It would be more profitable to tail allocate the folding set node
5410 // from the type, instead of the other way around, due to the greater
5411 // alignment requirements of the type. But this makes it harder to deal with
5412 // the different type node sizes. This would require either uniquing from
5413 // different folding sets, or having the folding setaccept a
5414 // contextual parameter which is not fixed at construction.
5415 Mem = Allocate(
5416 sizeof(TagTypeFoldingSetPlaceholder) +
5417 TagTypeFoldingSetPlaceholder::getOffset() + Size,
5418 std::max(alignof(TagTypeFoldingSetPlaceholder), alignof(TagType)));
5419 auto *T = new (Mem) TagTypeFoldingSetPlaceholder();
5420 Mem = T->getTagType();
5421 } else {
5422 Mem = Allocate(Size, alignof(TagType));
5423 }
5424
5425 auto *T = [&, TC = TC]() -> TagType * {
5426 switch (TC) {
5427 case Type::Enum: {
5428 assert(isa<EnumDecl>(TD));
5429 auto *T = new (Mem) EnumType(TC, Keyword, Qualifier, TD, OwnsTag,
5430 IsInjected, CanonicalType);
5431 assert(reinterpret_cast<void *>(T) ==
5432 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5433 "TagType must be the first base of EnumType");
5434 return T;
5435 }
5436 case Type::Record: {
5437 assert(isa<RecordDecl>(TD));
5438 auto *T = new (Mem) RecordType(TC, Keyword, Qualifier, TD, OwnsTag,
5439 IsInjected, CanonicalType);
5440 assert(reinterpret_cast<void *>(T) ==
5441 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5442 "TagType must be the first base of RecordType");
5443 return T;
5444 }
5445 case Type::InjectedClassName: {
5446 auto *T = new (Mem) InjectedClassNameType(Keyword, Qualifier, TD,
5447 IsInjected, CanonicalType);
5448 assert(reinterpret_cast<void *>(T) ==
5449 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5450 "TagType must be the first base of InjectedClassNameType");
5451 return T;
5452 }
5453 default:
5454 llvm_unreachable("unexpected type class");
5455 }
5456 }();
5457 assert(T->getKeyword() == Keyword);
5458 assert(T->getQualifier() == Qualifier);
5459 assert(T->getDecl() == TD);
5460 assert(T->isInjected() == IsInjected);
5461 assert(T->isTagOwned() == OwnsTag);
5462 assert((T->isCanonicalUnqualified()
5463 ? QualType()
5464 : T->getCanonicalTypeInternal()) == QualType(CanonicalType, 0));
5465 Types.push_back(T);
5466 return T;
5467}
5468
5469static const TagDecl *getNonInjectedClassName(const TagDecl *TD) {
5470 if (const auto *RD = dyn_cast<CXXRecordDecl>(TD);
5471 RD && RD->isInjectedClassName())
5472 return cast<TagDecl>(RD->getDeclContext());
5473 return TD;
5474}
5475
5478 if (TD->TypeForDecl)
5479 return TD->TypeForDecl->getCanonicalTypeUnqualified();
5480
5481 const Type *CanonicalType = getTagTypeInternal(
5483 /*Qualifier=*/std::nullopt, TD,
5484 /*OwnsTag=*/false, /*IsInjected=*/false, /*CanonicalType=*/nullptr,
5485 /*WithFoldingSetNode=*/false);
5486 TD->TypeForDecl = CanonicalType;
5487 return CanQualType::CreateUnsafe(QualType(CanonicalType, 0));
5488}
5489
5491 NestedNameSpecifier Qualifier,
5492 const TagDecl *TD, bool OwnsTag) const {
5493
5494 const TagDecl *NonInjectedTD = ::getNonInjectedClassName(TD);
5495 bool IsInjected = TD != NonInjectedTD;
5496
5497 ElaboratedTypeKeyword PreferredKeyword =
5500 NonInjectedTD->getTagKind());
5501
5502 if (Keyword == PreferredKeyword && !Qualifier && !OwnsTag) {
5503 if (const Type *T = TD->TypeForDecl; T && !T->isCanonicalUnqualified())
5504 return QualType(T, 0);
5505
5506 const Type *CanonicalType = getCanonicalTagType(NonInjectedTD).getTypePtr();
5507 const Type *T =
5508 getTagTypeInternal(Keyword,
5509 /*Qualifier=*/std::nullopt, NonInjectedTD,
5510 /*OwnsTag=*/false, IsInjected, CanonicalType,
5511 /*WithFoldingSetNode=*/false);
5512 TD->TypeForDecl = T;
5513 return QualType(T, 0);
5514 }
5515
5516 llvm::FoldingSetNodeID ID;
5517 TagTypeFoldingSetPlaceholder::Profile(ID, Keyword, Qualifier, NonInjectedTD,
5518 OwnsTag, IsInjected);
5519
5520 void *InsertPos = nullptr;
5521 if (TagTypeFoldingSetPlaceholder *T =
5522 TagTypes.FindNodeOrInsertPos(ID, InsertPos))
5523 return QualType(T->getTagType(), 0);
5524
5525 const Type *CanonicalType = getCanonicalTagType(NonInjectedTD).getTypePtr();
5526 TagType *T =
5527 getTagTypeInternal(Keyword, Qualifier, NonInjectedTD, OwnsTag, IsInjected,
5528 CanonicalType, /*WithFoldingSetNode=*/true);
5529 TagTypes.InsertNode(TagTypeFoldingSetPlaceholder::fromTagType(T), InsertPos);
5530 return QualType(T, 0);
5531}
5532
5533bool ASTContext::computeBestEnumTypes(bool IsPacked, unsigned NumNegativeBits,
5534 unsigned NumPositiveBits,
5535 QualType &BestType,
5536 QualType &BestPromotionType) {
5537 unsigned IntWidth = Target->getIntWidth();
5538 unsigned CharWidth = Target->getCharWidth();
5539 unsigned ShortWidth = Target->getShortWidth();
5540 bool EnumTooLarge = false;
5541 unsigned BestWidth;
5542 if (NumNegativeBits) {
5543 // If there is a negative value, figure out the smallest integer type (of
5544 // int/long/longlong) that fits.
5545 // If it's packed, check also if it fits a char or a short.
5546 if (IsPacked && NumNegativeBits <= CharWidth &&
5547 NumPositiveBits < CharWidth) {
5548 BestType = SignedCharTy;
5549 BestWidth = CharWidth;
5550 } else if (IsPacked && NumNegativeBits <= ShortWidth &&
5551 NumPositiveBits < ShortWidth) {
5552 BestType = ShortTy;
5553 BestWidth = ShortWidth;
5554 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
5555 BestType = IntTy;
5556 BestWidth = IntWidth;
5557 } else {
5558 BestWidth = Target->getLongWidth();
5559
5560 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
5561 BestType = LongTy;
5562 } else {
5563 BestWidth = Target->getLongLongWidth();
5564
5565 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
5566 EnumTooLarge = true;
5567 BestType = LongLongTy;
5568 }
5569 }
5570 BestPromotionType = (BestWidth <= IntWidth ? IntTy : BestType);
5571 } else {
5572 // If there is no negative value, figure out the smallest type that fits
5573 // all of the enumerator values.
5574 // If it's packed, check also if it fits a char or a short.
5575 if (IsPacked && NumPositiveBits <= CharWidth) {
5576 BestType = UnsignedCharTy;
5577 BestPromotionType = IntTy;
5578 BestWidth = CharWidth;
5579 } else if (IsPacked && NumPositiveBits <= ShortWidth) {
5580 BestType = UnsignedShortTy;
5581 BestPromotionType = IntTy;
5582 BestWidth = ShortWidth;
5583 } else if (NumPositiveBits <= IntWidth) {
5584 BestType = UnsignedIntTy;
5585 BestWidth = IntWidth;
5586 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5588 : IntTy;
5589 } else if (NumPositiveBits <= (BestWidth = Target->getLongWidth())) {
5590 BestType = UnsignedLongTy;
5591 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5593 : LongTy;
5594 } else {
5595 BestWidth = Target->getLongLongWidth();
5596 if (NumPositiveBits > BestWidth) {
5597 // This can happen with bit-precise integer types, but those are not
5598 // allowed as the type for an enumerator per C23 6.7.2.2p4 and p12.
5599 // FIXME: GCC uses __int128_t and __uint128_t for cases that fit within
5600 // a 128-bit integer, we should consider doing the same.
5601 EnumTooLarge = true;
5602 }
5603 BestType = UnsignedLongLongTy;
5604 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5606 : LongLongTy;
5607 }
5608 }
5609 return EnumTooLarge;
5610}
5611
5613 assert((T->isIntegralType(*this) || T->isEnumeralType()) &&
5614 "Integral type required!");
5615 unsigned BitWidth = getIntWidth(T);
5616
5617 if (Value.isUnsigned() || Value.isNonNegative()) {
5618 if (T->isSignedIntegerOrEnumerationType())
5619 --BitWidth;
5620 return Value.getActiveBits() <= BitWidth;
5621 }
5622 return Value.getSignificantBits() <= BitWidth;
5623}
5624
5625UnresolvedUsingType *ASTContext::getUnresolvedUsingTypeInternal(
5627 const UnresolvedUsingTypenameDecl *D, void *InsertPos,
5628 const Type *CanonicalType) const {
5629 void *Mem = Allocate(
5630 UnresolvedUsingType::totalSizeToAlloc<
5632 !!InsertPos, !!Qualifier),
5633 alignof(UnresolvedUsingType));
5634 auto *T = new (Mem) UnresolvedUsingType(Keyword, Qualifier, D, CanonicalType);
5635 if (InsertPos) {
5636 auto *Placeholder = new (T->getFoldingSetPlaceholder())
5638 TypedefTypes.InsertNode(Placeholder, InsertPos);
5639 }
5640 Types.push_back(T);
5641 return T;
5642}
5643
5645 const UnresolvedUsingTypenameDecl *D) const {
5646 D = D->getCanonicalDecl();
5647 if (D->TypeForDecl)
5648 return D->TypeForDecl->getCanonicalTypeUnqualified();
5649
5650 const Type *CanonicalType = getUnresolvedUsingTypeInternal(
5652 /*Qualifier=*/std::nullopt, D,
5653 /*InsertPos=*/nullptr, /*CanonicalType=*/nullptr);
5654 D->TypeForDecl = CanonicalType;
5655 return CanQualType::CreateUnsafe(QualType(CanonicalType, 0));
5656}
5657
5660 NestedNameSpecifier Qualifier,
5661 const UnresolvedUsingTypenameDecl *D) const {
5662 if (Keyword == ElaboratedTypeKeyword::None && !Qualifier) {
5663 if (const Type *T = D->TypeForDecl; T && !T->isCanonicalUnqualified())
5664 return QualType(T, 0);
5665
5666 const Type *CanonicalType = getCanonicalUnresolvedUsingType(D).getTypePtr();
5667 const Type *T =
5668 getUnresolvedUsingTypeInternal(ElaboratedTypeKeyword::None,
5669 /*Qualifier=*/std::nullopt, D,
5670 /*InsertPos=*/nullptr, CanonicalType);
5671 D->TypeForDecl = T;
5672 return QualType(T, 0);
5673 }
5674
5675 llvm::FoldingSetNodeID ID;
5676 UnresolvedUsingType::Profile(ID, Keyword, Qualifier, D);
5677
5678 void *InsertPos = nullptr;
5680 UnresolvedUsingTypes.FindNodeOrInsertPos(ID, InsertPos))
5681 return QualType(Placeholder->getType(), 0);
5682 assert(InsertPos);
5683
5684 const Type *CanonicalType = getCanonicalUnresolvedUsingType(D).getTypePtr();
5685 const Type *T = getUnresolvedUsingTypeInternal(Keyword, Qualifier, D,
5686 InsertPos, CanonicalType);
5687 return QualType(T, 0);
5688}
5689
5691 QualType modifiedType,
5692 QualType equivalentType,
5693 const Attr *attr) const {
5694 llvm::FoldingSetNodeID id;
5695 AttributedType::Profile(id, attrKind, modifiedType, equivalentType, attr);
5696
5697 void *insertPos = nullptr;
5698 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
5699 if (type) return QualType(type, 0);
5700
5701 assert(!attr || attr->getKind() == attrKind);
5702
5703 QualType canon = getCanonicalType(equivalentType);
5704 type = new (*this, alignof(AttributedType))
5705 AttributedType(canon, attrKind, attr, modifiedType, equivalentType);
5706
5707 Types.push_back(type);
5708 AttributedTypes.InsertNode(type, insertPos);
5709
5710 return QualType(type, 0);
5711}
5712
5714 QualType equivalentType) const {
5715 return getAttributedType(attr->getKind(), modifiedType, equivalentType, attr);
5716}
5717
5719 QualType modifiedType,
5720 QualType equivalentType) {
5721 switch (nullability) {
5723 return getAttributedType(attr::TypeNonNull, modifiedType, equivalentType);
5724
5726 return getAttributedType(attr::TypeNullable, modifiedType, equivalentType);
5727
5729 return getAttributedType(attr::TypeNullableResult, modifiedType,
5730 equivalentType);
5731
5733 return getAttributedType(attr::TypeNullUnspecified, modifiedType,
5734 equivalentType);
5735 }
5736
5737 llvm_unreachable("Unknown nullability kind");
5738}
5739
5740QualType ASTContext::getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
5741 QualType Wrapped) const {
5742 llvm::FoldingSetNodeID ID;
5743 BTFTagAttributedType::Profile(ID, Wrapped, BTFAttr);
5744
5745 void *InsertPos = nullptr;
5746 BTFTagAttributedType *Ty =
5747 BTFTagAttributedTypes.FindNodeOrInsertPos(ID, InsertPos);
5748 if (Ty)
5749 return QualType(Ty, 0);
5750
5751 QualType Canon = getCanonicalType(Wrapped);
5752 Ty = new (*this, alignof(BTFTagAttributedType))
5753 BTFTagAttributedType(Canon, Wrapped, BTFAttr);
5754
5755 Types.push_back(Ty);
5756 BTFTagAttributedTypes.InsertNode(Ty, InsertPos);
5757
5758 return QualType(Ty, 0);
5759}
5760
5762 QualType Underlying) const {
5763 const IdentifierInfo *II = Attr->getBehaviorKind();
5764 StringRef IdentName = II->getName();
5765 OverflowBehaviorType::OverflowBehaviorKind Kind;
5766 if (IdentName == "wrap") {
5767 Kind = OverflowBehaviorType::OverflowBehaviorKind::Wrap;
5768 } else if (IdentName == "trap") {
5769 Kind = OverflowBehaviorType::OverflowBehaviorKind::Trap;
5770 } else {
5771 return Underlying;
5772 }
5773
5774 return getOverflowBehaviorType(Kind, Underlying);
5775}
5776
5778 OverflowBehaviorType::OverflowBehaviorKind Kind,
5779 QualType Underlying) const {
5780 assert(!Underlying->isOverflowBehaviorType() &&
5781 "Cannot have underlying types that are themselves OBTs");
5782 llvm::FoldingSetNodeID ID;
5783 OverflowBehaviorType::Profile(ID, Underlying, Kind);
5784 void *InsertPos = nullptr;
5785
5786 if (OverflowBehaviorType *OBT =
5787 OverflowBehaviorTypes.FindNodeOrInsertPos(ID, InsertPos)) {
5788 return QualType(OBT, 0);
5789 }
5790
5791 QualType Canonical;
5792 if (!Underlying.isCanonical() || Underlying.hasLocalQualifiers()) {
5793 SplitQualType canonSplit = getCanonicalType(Underlying).split();
5794 Canonical = getOverflowBehaviorType(Kind, QualType(canonSplit.Ty, 0));
5795 Canonical = getQualifiedType(Canonical, canonSplit.Quals);
5796 assert(!OverflowBehaviorTypes.FindNodeOrInsertPos(ID, InsertPos) &&
5797 "Shouldn't be in the map");
5798 }
5799
5800 OverflowBehaviorType *Ty = new (*this, alignof(OverflowBehaviorType))
5801 OverflowBehaviorType(Canonical, Underlying, Kind);
5802
5803 Types.push_back(Ty);
5804 OverflowBehaviorTypes.InsertNode(Ty, InsertPos);
5805 return QualType(Ty, 0);
5806}
5807
5809 QualType Wrapped, QualType Contained,
5810 const HLSLAttributedResourceType::Attributes &Attrs) {
5811
5812 llvm::FoldingSetNodeID ID;
5813 HLSLAttributedResourceType::Profile(ID, Wrapped, Contained, Attrs);
5814
5815 void *InsertPos = nullptr;
5816 HLSLAttributedResourceType *Ty =
5817 HLSLAttributedResourceTypes.FindNodeOrInsertPos(ID, InsertPos);
5818 if (Ty)
5819 return QualType(Ty, 0);
5820
5821 Ty = new (*this, alignof(HLSLAttributedResourceType))
5822 HLSLAttributedResourceType(Wrapped, Contained, Attrs);
5823
5824 Types.push_back(Ty);
5825 HLSLAttributedResourceTypes.InsertNode(Ty, InsertPos);
5826
5827 return QualType(Ty, 0);
5828}
5829
5830QualType ASTContext::getHLSLInlineSpirvType(uint32_t Opcode, uint32_t Size,
5831 uint32_t Alignment,
5832 ArrayRef<SpirvOperand> Operands) {
5833 llvm::FoldingSetNodeID ID;
5834 HLSLInlineSpirvType::Profile(ID, Opcode, Size, Alignment, Operands);
5835
5836 void *InsertPos = nullptr;
5837 HLSLInlineSpirvType *Ty =
5838 HLSLInlineSpirvTypes.FindNodeOrInsertPos(ID, InsertPos);
5839 if (Ty)
5840 return QualType(Ty, 0);
5841
5842 void *Mem = Allocate(
5843 HLSLInlineSpirvType::totalSizeToAlloc<SpirvOperand>(Operands.size()),
5844 alignof(HLSLInlineSpirvType));
5845
5846 Ty = new (Mem) HLSLInlineSpirvType(Opcode, Size, Alignment, Operands);
5847
5848 Types.push_back(Ty);
5849 HLSLInlineSpirvTypes.InsertNode(Ty, InsertPos);
5850
5851 return QualType(Ty, 0);
5852}
5853
5854/// Retrieve a substitution-result type.
5856 Decl *AssociatedDecl,
5857 unsigned Index,
5858 UnsignedOrNone PackIndex,
5859 bool Final) const {
5860 llvm::FoldingSetNodeID ID;
5861 SubstTemplateTypeParmType::Profile(ID, Replacement, AssociatedDecl, Index,
5862 PackIndex, Final);
5863 void *InsertPos = nullptr;
5864 SubstTemplateTypeParmType *SubstParm =
5865 SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
5866
5867 if (!SubstParm) {
5868 void *Mem = Allocate(SubstTemplateTypeParmType::totalSizeToAlloc<QualType>(
5869 !Replacement.isCanonical()),
5870 alignof(SubstTemplateTypeParmType));
5871 SubstParm = new (Mem) SubstTemplateTypeParmType(Replacement, AssociatedDecl,
5872 Index, PackIndex, Final);
5873 Types.push_back(SubstParm);
5874 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
5875 }
5876
5877 return QualType(SubstParm, 0);
5878}
5879
5882 unsigned Index, bool Final,
5883 const TemplateArgument &ArgPack) {
5884#ifndef NDEBUG
5885 for (const auto &P : ArgPack.pack_elements())
5886 assert(P.getKind() == TemplateArgument::Type && "Pack contains a non-type");
5887#endif
5888
5889 llvm::FoldingSetNodeID ID;
5890 SubstTemplateTypeParmPackType::Profile(ID, AssociatedDecl, Index, Final,
5891 ArgPack);
5892 void *InsertPos = nullptr;
5893 if (SubstTemplateTypeParmPackType *SubstParm =
5894 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
5895 return QualType(SubstParm, 0);
5896
5897 QualType Canon;
5898 {
5899 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(ArgPack);
5900 if (!AssociatedDecl->isCanonicalDecl() ||
5901 !CanonArgPack.structurallyEquals(ArgPack)) {
5903 AssociatedDecl->getCanonicalDecl(), Index, Final, CanonArgPack);
5904 [[maybe_unused]] const auto *Nothing =
5905 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
5906 assert(!Nothing);
5907 }
5908 }
5909
5910 auto *SubstParm = new (*this, alignof(SubstTemplateTypeParmPackType))
5911 SubstTemplateTypeParmPackType(Canon, AssociatedDecl, Index, Final,
5912 ArgPack);
5913 Types.push_back(SubstParm);
5914 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
5915 return QualType(SubstParm, 0);
5916}
5917
5920 assert(llvm::all_of(ArgPack.pack_elements(),
5921 [](const auto &P) {
5922 return P.getKind() == TemplateArgument::Type;
5923 }) &&
5924 "Pack contains a non-type");
5925
5926 llvm::FoldingSetNodeID ID;
5927 SubstBuiltinTemplatePackType::Profile(ID, ArgPack);
5928
5929 void *InsertPos = nullptr;
5930 if (auto *T =
5931 SubstBuiltinTemplatePackTypes.FindNodeOrInsertPos(ID, InsertPos))
5932 return QualType(T, 0);
5933
5934 QualType Canon;
5935 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(ArgPack);
5936 if (!CanonArgPack.structurallyEquals(ArgPack)) {
5937 Canon = getSubstBuiltinTemplatePack(CanonArgPack);
5938 // Refresh InsertPos, in case the recursive call above caused rehashing,
5939 // which would invalidate the bucket pointer.
5940 [[maybe_unused]] const auto *Nothing =
5941 SubstBuiltinTemplatePackTypes.FindNodeOrInsertPos(ID, InsertPos);
5942 assert(!Nothing);
5943 }
5944
5945 auto *PackType = new (*this, alignof(SubstBuiltinTemplatePackType))
5946 SubstBuiltinTemplatePackType(Canon, ArgPack);
5947 Types.push_back(PackType);
5948 SubstBuiltinTemplatePackTypes.InsertNode(PackType, InsertPos);
5949 return QualType(PackType, 0);
5950}
5951
5952/// Retrieve the template type parameter type for a template
5953/// parameter or parameter pack with the given depth, index, and (optionally)
5954/// name.
5955QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
5956 bool ParameterPack,
5957 TemplateTypeParmDecl *TTPDecl) const {
5958 llvm::FoldingSetNodeID ID;
5959 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
5960 void *InsertPos = nullptr;
5961 TemplateTypeParmType *TypeParm
5962 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
5963
5964 if (TypeParm)
5965 return QualType(TypeParm, 0);
5966
5967 if (TTPDecl) {
5968 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
5969 TypeParm = new (*this, alignof(TemplateTypeParmType))
5970 TemplateTypeParmType(Depth, Index, ParameterPack, TTPDecl, Canon);
5971
5972 TemplateTypeParmType *TypeCheck
5973 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
5974 assert(!TypeCheck && "Template type parameter canonical type broken");
5975 (void)TypeCheck;
5976 } else
5977 TypeParm = new (*this, alignof(TemplateTypeParmType)) TemplateTypeParmType(
5978 Depth, Index, ParameterPack, /*TTPDecl=*/nullptr, /*Canon=*/QualType());
5979
5980 Types.push_back(TypeParm);
5981 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
5982
5983 return QualType(TypeParm, 0);
5984}
5985
5988 switch (Keyword) {
5989 // These are just themselves.
5995 return Keyword;
5996
5997 // These are equivalent.
6000
6001 // These are functionally equivalent, so relying on their equivalence is
6002 // IFNDR. By making them equivalent, we disallow overloading, which at least
6003 // can produce a diagnostic.
6006 }
6007 llvm_unreachable("unexpected keyword kind");
6008}
6009
6011 ElaboratedTypeKeyword Keyword, SourceLocation ElaboratedKeywordLoc,
6012 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKeywordLoc,
6013 TemplateName Name, SourceLocation NameLoc,
6014 const TemplateArgumentListInfo &SpecifiedArgs,
6015 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6017 Keyword, Name, SpecifiedArgs.arguments(), CanonicalArgs, Underlying);
6018
6021 ElaboratedKeywordLoc, QualifierLoc, TemplateKeywordLoc, NameLoc,
6022 SpecifiedArgs);
6023 return TSI;
6024}
6025
6028 ArrayRef<TemplateArgumentLoc> SpecifiedArgs,
6029 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6030 SmallVector<TemplateArgument, 4> SpecifiedArgVec;
6031 SpecifiedArgVec.reserve(SpecifiedArgs.size());
6032 for (const TemplateArgumentLoc &Arg : SpecifiedArgs)
6033 SpecifiedArgVec.push_back(Arg.getArgument());
6034
6035 return getTemplateSpecializationType(Keyword, Template, SpecifiedArgVec,
6036 CanonicalArgs, Underlying);
6037}
6038
6039[[maybe_unused]] static bool
6041 for (const TemplateArgument &Arg : Args)
6042 if (Arg.isPackExpansion())
6043 return true;
6044 return false;
6045}
6046
6049 ArrayRef<TemplateArgument> Args) const {
6050 assert(Template ==
6051 getCanonicalTemplateName(Template, /*IgnoreDeduced=*/true));
6053 Template.getAsDependentTemplateName()));
6054#ifndef NDEBUG
6055 for (const auto &Arg : Args)
6056 assert(Arg.structurallyEquals(getCanonicalTemplateArgument(Arg)));
6057#endif
6058
6059 llvm::FoldingSetNodeID ID;
6060 TemplateSpecializationType::Profile(ID, Keyword, Template, Args, QualType(),
6061 *this);
6062 void *InsertPos = nullptr;
6063 if (auto *T = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
6064 return QualType(T, 0);
6065
6066 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
6067 sizeof(TemplateArgument) * Args.size(),
6068 alignof(TemplateSpecializationType));
6069 auto *Spec =
6070 new (Mem) TemplateSpecializationType(Keyword, Template,
6071 /*IsAlias=*/false, Args, QualType());
6072 assert(Spec->isDependentType() &&
6073 "canonical template specialization must be dependent");
6074 Types.push_back(Spec);
6075 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
6076 return QualType(Spec, 0);
6077}
6078
6081 ArrayRef<TemplateArgument> SpecifiedArgs,
6082 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6083 const auto *TD = Template.getAsTemplateDecl(/*IgnoreDeduced=*/true);
6084 bool IsTypeAlias = TD && TD->isTypeAlias();
6085 if (Underlying.isNull()) {
6086 TemplateName CanonTemplate =
6087 getCanonicalTemplateName(Template, /*IgnoreDeduced=*/true);
6088 ElaboratedTypeKeyword CanonKeyword =
6089 CanonTemplate.getAsDependentTemplateName()
6092 bool NonCanonical = Template != CanonTemplate || Keyword != CanonKeyword;
6094 if (CanonicalArgs.empty()) {
6095 CanonArgsVec = SmallVector<TemplateArgument, 4>(SpecifiedArgs);
6096 NonCanonical |= canonicalizeTemplateArguments(CanonArgsVec);
6097 CanonicalArgs = CanonArgsVec;
6098 } else {
6099 NonCanonical |= !llvm::equal(
6100 SpecifiedArgs, CanonicalArgs,
6101 [](const TemplateArgument &A, const TemplateArgument &B) {
6102 return A.structurallyEquals(B);
6103 });
6104 }
6105
6106 // We can get here with an alias template when the specialization
6107 // contains a pack expansion that does not match up with a parameter
6108 // pack, or a builtin template which cannot be resolved due to dependency.
6109 assert((!isa_and_nonnull<TypeAliasTemplateDecl>(TD) ||
6110 hasAnyPackExpansions(CanonicalArgs)) &&
6111 "Caller must compute aliased type");
6112 IsTypeAlias = false;
6113
6115 CanonKeyword, CanonTemplate, CanonicalArgs);
6116 if (!NonCanonical)
6117 return Underlying;
6118 }
6119 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
6120 sizeof(TemplateArgument) * SpecifiedArgs.size() +
6121 (IsTypeAlias ? sizeof(QualType) : 0),
6122 alignof(TemplateSpecializationType));
6123 auto *Spec = new (Mem) TemplateSpecializationType(
6124 Keyword, Template, IsTypeAlias, SpecifiedArgs, Underlying);
6125 Types.push_back(Spec);
6126 return QualType(Spec, 0);
6127}
6128
6131 llvm::FoldingSetNodeID ID;
6132 ParenType::Profile(ID, InnerType);
6133
6134 void *InsertPos = nullptr;
6135 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
6136 if (T)
6137 return QualType(T, 0);
6138
6139 QualType Canon = InnerType;
6140 if (!Canon.isCanonical()) {
6141 Canon = getCanonicalType(InnerType);
6142 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
6143 assert(!CheckT && "Paren canonical type broken");
6144 (void)CheckT;
6145 }
6146
6147 T = new (*this, alignof(ParenType)) ParenType(InnerType, Canon);
6148 Types.push_back(T);
6149 ParenTypes.InsertNode(T, InsertPos);
6150 return QualType(T, 0);
6151}
6152
6155 const IdentifierInfo *MacroII) const {
6156 QualType Canon = UnderlyingTy;
6157 if (!Canon.isCanonical())
6158 Canon = getCanonicalType(UnderlyingTy);
6159
6160 auto *newType = new (*this, alignof(MacroQualifiedType))
6161 MacroQualifiedType(UnderlyingTy, Canon, MacroII);
6162 Types.push_back(newType);
6163 return QualType(newType, 0);
6164}
6165
6168 const IdentifierInfo *Name) const {
6169 llvm::FoldingSetNodeID ID;
6170 DependentNameType::Profile(ID, Keyword, NNS, Name);
6171
6172 void *InsertPos = nullptr;
6173 if (DependentNameType *T =
6174 DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos))
6175 return QualType(T, 0);
6176
6177 ElaboratedTypeKeyword CanonKeyword =
6179 NestedNameSpecifier CanonNNS = NNS.getCanonical();
6180
6181 QualType Canon;
6182 if (CanonKeyword != Keyword || CanonNNS != NNS) {
6183 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
6184 [[maybe_unused]] DependentNameType *T =
6185 DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
6186 assert(!T && "broken canonicalization");
6187 assert(Canon.isCanonical());
6188 }
6189
6190 DependentNameType *T = new (*this, alignof(DependentNameType))
6191 DependentNameType(Keyword, NNS, Name, Canon);
6192 Types.push_back(T);
6193 DependentNameTypes.InsertNode(T, InsertPos);
6194 return QualType(T, 0);
6195}
6196
6198 TemplateArgument Arg;
6199 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
6201 if (TTP->isParameterPack())
6202 ArgType = getPackExpansionType(ArgType, std::nullopt);
6203
6205 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
6206 QualType T =
6207 NTTP->getType().getNonPackExpansionType().getNonLValueExprType(*this);
6208 // For class NTTPs, ensure we include the 'const' so the type matches that
6209 // of a real template argument.
6210 // FIXME: It would be more faithful to model this as something like an
6211 // lvalue-to-rvalue conversion applied to a const-qualified lvalue.
6213 if (T->isRecordType()) {
6214 // C++ [temp.param]p8: An id-expression naming a non-type
6215 // template-parameter of class type T denotes a static storage duration
6216 // object of type const T.
6217 T.addConst();
6218 VK = VK_LValue;
6219 } else {
6220 VK = Expr::getValueKindForType(NTTP->getType());
6221 }
6222 Expr *E = new (*this)
6223 DeclRefExpr(*this, NTTP, /*RefersToEnclosingVariableOrCapture=*/false,
6224 T, VK, NTTP->getLocation());
6225
6226 if (NTTP->isParameterPack())
6227 E = new (*this) PackExpansionExpr(E, NTTP->getLocation(), std::nullopt);
6228 Arg = TemplateArgument(E, /*IsCanonical=*/false);
6229 } else {
6230 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
6232 /*Qualifier=*/std::nullopt, /*TemplateKeyword=*/false,
6233 TemplateName(TTP));
6234 if (TTP->isParameterPack())
6235 Arg = TemplateArgument(Name, /*NumExpansions=*/std::nullopt);
6236 else
6237 Arg = TemplateArgument(Name);
6238 }
6239
6240 if (Param->isTemplateParameterPack())
6241 Arg =
6242 TemplateArgument::CreatePackCopy(const_cast<ASTContext &>(*this), Arg);
6243
6244 return Arg;
6245}
6246
6248 UnsignedOrNone NumExpansions,
6249 bool ExpectPackInType) const {
6250 assert((!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) &&
6251 "Pack expansions must expand one or more parameter packs");
6252
6253 llvm::FoldingSetNodeID ID;
6254 PackExpansionType::Profile(ID, Pattern, NumExpansions);
6255
6256 void *InsertPos = nullptr;
6257 PackExpansionType *T = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
6258 if (T)
6259 return QualType(T, 0);
6260
6261 QualType Canon;
6262 if (!Pattern.isCanonical()) {
6263 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions,
6264 /*ExpectPackInType=*/false);
6265
6266 // Find the insert position again, in case we inserted an element into
6267 // PackExpansionTypes and invalidated our insert position.
6268 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
6269 }
6270
6271 T = new (*this, alignof(PackExpansionType))
6272 PackExpansionType(Pattern, Canon, NumExpansions);
6273 Types.push_back(T);
6274 PackExpansionTypes.InsertNode(T, InsertPos);
6275 return QualType(T, 0);
6276}
6277
6278/// CmpProtocolNames - Comparison predicate for sorting protocols
6279/// alphabetically.
6280static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
6281 ObjCProtocolDecl *const *RHS) {
6282 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
6283}
6284
6286 if (Protocols.empty()) return true;
6287
6288 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
6289 return false;
6290
6291 for (unsigned i = 1; i != Protocols.size(); ++i)
6292 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
6293 Protocols[i]->getCanonicalDecl() != Protocols[i])
6294 return false;
6295 return true;
6296}
6297
6298static void
6300 // Sort protocols, keyed by name.
6301 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
6302
6303 // Canonicalize.
6304 for (ObjCProtocolDecl *&P : Protocols)
6305 P = P->getCanonicalDecl();
6306
6307 // Remove duplicates.
6308 auto ProtocolsEnd = llvm::unique(Protocols);
6309 Protocols.erase(ProtocolsEnd, Protocols.end());
6310}
6311
6313 ObjCProtocolDecl * const *Protocols,
6314 unsigned NumProtocols) const {
6315 return getObjCObjectType(BaseType, {}, ArrayRef(Protocols, NumProtocols),
6316 /*isKindOf=*/false);
6317}
6318
6320 QualType baseType,
6321 ArrayRef<QualType> typeArgs,
6323 bool isKindOf) const {
6324 // If the base type is an interface and there aren't any protocols or
6325 // type arguments to add, then the interface type will do just fine.
6326 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
6327 isa<ObjCInterfaceType>(baseType))
6328 return baseType;
6329
6330 // Look in the folding set for an existing type.
6331 llvm::FoldingSetNodeID ID;
6332 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
6333 void *InsertPos = nullptr;
6334 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
6335 return QualType(QT, 0);
6336
6337 // Determine the type arguments to be used for canonicalization,
6338 // which may be explicitly specified here or written on the base
6339 // type.
6340 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
6341 if (effectiveTypeArgs.empty()) {
6342 if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
6343 effectiveTypeArgs = baseObject->getTypeArgs();
6344 }
6345
6346 // Build the canonical type, which has the canonical base type and a
6347 // sorted-and-uniqued list of protocols and the type arguments
6348 // canonicalized.
6349 QualType canonical;
6350 bool typeArgsAreCanonical = llvm::all_of(
6351 effectiveTypeArgs, [&](QualType type) { return type.isCanonical(); });
6352 bool protocolsSorted = areSortedAndUniqued(protocols);
6353 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
6354 // Determine the canonical type arguments.
6355 ArrayRef<QualType> canonTypeArgs;
6356 SmallVector<QualType, 4> canonTypeArgsVec;
6357 if (!typeArgsAreCanonical) {
6358 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
6359 for (auto typeArg : effectiveTypeArgs)
6360 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
6361 canonTypeArgs = canonTypeArgsVec;
6362 } else {
6363 canonTypeArgs = effectiveTypeArgs;
6364 }
6365
6366 ArrayRef<ObjCProtocolDecl *> canonProtocols;
6367 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
6368 if (!protocolsSorted) {
6369 canonProtocolsVec.append(protocols.begin(), protocols.end());
6370 SortAndUniqueProtocols(canonProtocolsVec);
6371 canonProtocols = canonProtocolsVec;
6372 } else {
6373 canonProtocols = protocols;
6374 }
6375
6376 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
6377 canonProtocols, isKindOf);
6378
6379 // Regenerate InsertPos.
6380 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
6381 }
6382
6383 unsigned size = sizeof(ObjCObjectTypeImpl);
6384 size += typeArgs.size() * sizeof(QualType);
6385 size += protocols.size() * sizeof(ObjCProtocolDecl *);
6386 void *mem = Allocate(size, alignof(ObjCObjectTypeImpl));
6387 auto *T =
6388 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
6389 isKindOf);
6390
6391 Types.push_back(T);
6392 ObjCObjectTypes.InsertNode(T, InsertPos);
6393 return QualType(T, 0);
6394}
6395
6396/// Apply Objective-C protocol qualifiers to the given type.
6397/// If this is for the canonical type of a type parameter, we can apply
6398/// protocol qualifiers on the ObjCObjectPointerType.
6401 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
6402 bool allowOnPointerType) const {
6403 hasError = false;
6404
6405 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
6406 return getObjCTypeParamType(objT->getDecl(), protocols);
6407 }
6408
6409 // Apply protocol qualifiers to ObjCObjectPointerType.
6410 if (allowOnPointerType) {
6411 if (const auto *objPtr =
6412 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
6413 const ObjCObjectType *objT = objPtr->getObjectType();
6414 // Merge protocol lists and construct ObjCObjectType.
6416 protocolsVec.append(objT->qual_begin(),
6417 objT->qual_end());
6418 protocolsVec.append(protocols.begin(), protocols.end());
6419 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
6421 objT->getBaseType(),
6422 objT->getTypeArgsAsWritten(),
6423 protocols,
6424 objT->isKindOfTypeAsWritten());
6426 }
6427 }
6428
6429 // Apply protocol qualifiers to ObjCObjectType.
6430 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
6431 // FIXME: Check for protocols to which the class type is already
6432 // known to conform.
6433
6434 return getObjCObjectType(objT->getBaseType(),
6435 objT->getTypeArgsAsWritten(),
6436 protocols,
6437 objT->isKindOfTypeAsWritten());
6438 }
6439
6440 // If the canonical type is ObjCObjectType, ...
6441 if (type->isObjCObjectType()) {
6442 // Silently overwrite any existing protocol qualifiers.
6443 // TODO: determine whether that's the right thing to do.
6444
6445 // FIXME: Check for protocols to which the class type is already
6446 // known to conform.
6447 return getObjCObjectType(type, {}, protocols, false);
6448 }
6449
6450 // id<protocol-list>
6451 if (type->isObjCIdType()) {
6452 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6453 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
6454 objPtr->isKindOfType());
6456 }
6457
6458 // Class<protocol-list>
6459 if (type->isObjCClassType()) {
6460 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6461 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
6462 objPtr->isKindOfType());
6464 }
6465
6466 hasError = true;
6467 return type;
6468}
6469
6472 ArrayRef<ObjCProtocolDecl *> protocols) const {
6473 // Look in the folding set for an existing type.
6474 llvm::FoldingSetNodeID ID;
6475 ObjCTypeParamType::Profile(ID, Decl, Decl->getUnderlyingType(), protocols);
6476 void *InsertPos = nullptr;
6477 if (ObjCTypeParamType *TypeParam =
6478 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
6479 return QualType(TypeParam, 0);
6480
6481 // We canonicalize to the underlying type.
6482 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
6483 if (!protocols.empty()) {
6484 // Apply the protocol qualifers.
6485 bool hasError;
6487 Canonical, protocols, hasError, true /*allowOnPointerType*/));
6488 assert(!hasError && "Error when apply protocol qualifier to bound type");
6489 }
6490
6491 unsigned size = sizeof(ObjCTypeParamType);
6492 size += protocols.size() * sizeof(ObjCProtocolDecl *);
6493 void *mem = Allocate(size, alignof(ObjCTypeParamType));
6494 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
6495
6496 Types.push_back(newType);
6497 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
6498 return QualType(newType, 0);
6499}
6500
6502 ObjCTypeParamDecl *New) const {
6503 New->setTypeSourceInfo(getTrivialTypeSourceInfo(Orig->getUnderlyingType()));
6504 // Update TypeForDecl after updating TypeSourceInfo.
6505 auto *NewTypeParamTy = cast<ObjCTypeParamType>(New->TypeForDecl);
6507 protocols.append(NewTypeParamTy->qual_begin(), NewTypeParamTy->qual_end());
6508 QualType UpdatedTy = getObjCTypeParamType(New, protocols);
6509 New->TypeForDecl = UpdatedTy.getTypePtr();
6510}
6511
6512/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
6513/// protocol list adopt all protocols in QT's qualified-id protocol
6514/// list.
6516 ObjCInterfaceDecl *IC) {
6517 if (!QT->isObjCQualifiedIdType())
6518 return false;
6519
6520 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
6521 // If both the right and left sides have qualifiers.
6522 for (auto *Proto : OPT->quals()) {
6523 if (!IC->ClassImplementsProtocol(Proto, false))
6524 return false;
6525 }
6526 return true;
6527 }
6528 return false;
6529}
6530
6531/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
6532/// QT's qualified-id protocol list adopt all protocols in IDecl's list
6533/// of protocols.
6535 ObjCInterfaceDecl *IDecl) {
6536 if (!QT->isObjCQualifiedIdType())
6537 return false;
6538 const auto *OPT = QT->getAs<ObjCObjectPointerType>();
6539 if (!OPT)
6540 return false;
6541 if (!IDecl->hasDefinition())
6542 return false;
6544 CollectInheritedProtocols(IDecl, InheritedProtocols);
6545 if (InheritedProtocols.empty())
6546 return false;
6547 // Check that if every protocol in list of id<plist> conforms to a protocol
6548 // of IDecl's, then bridge casting is ok.
6549 bool Conforms = false;
6550 for (auto *Proto : OPT->quals()) {
6551 Conforms = false;
6552 for (auto *PI : InheritedProtocols) {
6553 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
6554 Conforms = true;
6555 break;
6556 }
6557 }
6558 if (!Conforms)
6559 break;
6560 }
6561 if (Conforms)
6562 return true;
6563
6564 for (auto *PI : InheritedProtocols) {
6565 // If both the right and left sides have qualifiers.
6566 bool Adopts = false;
6567 for (auto *Proto : OPT->quals()) {
6568 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
6569 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
6570 break;
6571 }
6572 if (!Adopts)
6573 return false;
6574 }
6575 return true;
6576}
6577
6578/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
6579/// the given object type.
6581 llvm::FoldingSetNodeID ID;
6582 ObjCObjectPointerType::Profile(ID, ObjectT);
6583
6584 void *InsertPos = nullptr;
6585 if (ObjCObjectPointerType *QT =
6586 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
6587 return QualType(QT, 0);
6588
6589 // Find the canonical object type.
6590 QualType Canonical;
6591 if (!ObjectT.isCanonical()) {
6592 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
6593
6594 // Regenerate InsertPos.
6595 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
6596 }
6597
6598 // No match.
6599 void *Mem =
6601 auto *QType =
6602 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
6603
6604 Types.push_back(QType);
6605 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
6606 return QualType(QType, 0);
6607}
6608
6609/// getObjCInterfaceType - Return the unique reference to the type for the
6610/// specified ObjC interface decl. The list of protocols is optional.
6612 ObjCInterfaceDecl *PrevDecl) const {
6613 if (Decl->TypeForDecl)
6614 return QualType(Decl->TypeForDecl, 0);
6615
6616 if (PrevDecl) {
6617 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
6618 Decl->TypeForDecl = PrevDecl->TypeForDecl;
6619 return QualType(PrevDecl->TypeForDecl, 0);
6620 }
6621
6622 // Prefer the definition, if there is one.
6623 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
6624 Decl = Def;
6625
6626 void *Mem = Allocate(sizeof(ObjCInterfaceType), alignof(ObjCInterfaceType));
6627 auto *T = new (Mem) ObjCInterfaceType(Decl);
6628 Decl->TypeForDecl = T;
6629 Types.push_back(T);
6630 return QualType(T, 0);
6631}
6632
6633/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
6634/// TypeOfExprType AST's (since expression's are never shared). For example,
6635/// multiple declarations that refer to "typeof(x)" all contain different
6636/// DeclRefExpr's. This doesn't effect the type checker, since it operates
6637/// on canonical type's (which are always unique).
6639 TypeOfExprType *toe;
6640 if (tofExpr->isTypeDependent()) {
6641 llvm::FoldingSetNodeID ID;
6642 DependentTypeOfExprType::Profile(ID, *this, tofExpr,
6643 Kind == TypeOfKind::Unqualified);
6644
6645 void *InsertPos = nullptr;
6647 DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
6648 if (Canon) {
6649 // We already have a "canonical" version of an identical, dependent
6650 // typeof(expr) type. Use that as our canonical type.
6651 toe = new (*this, alignof(TypeOfExprType)) TypeOfExprType(
6652 *this, tofExpr, Kind, QualType((TypeOfExprType *)Canon, 0));
6653 } else {
6654 // Build a new, canonical typeof(expr) type.
6655 Canon = new (*this, alignof(DependentTypeOfExprType))
6656 DependentTypeOfExprType(*this, tofExpr, Kind);
6657 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
6658 toe = Canon;
6659 }
6660 } else {
6661 QualType Canonical = getCanonicalType(tofExpr->getType());
6662 toe = new (*this, alignof(TypeOfExprType))
6663 TypeOfExprType(*this, tofExpr, Kind, Canonical);
6664 }
6665 Types.push_back(toe);
6666 return QualType(toe, 0);
6667}
6668
6669/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
6670/// TypeOfType nodes. The only motivation to unique these nodes would be
6671/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
6672/// an issue. This doesn't affect the type checker, since it operates
6673/// on canonical types (which are always unique).
6675 QualType Canonical = getCanonicalType(tofType);
6676 auto *tot = new (*this, alignof(TypeOfType))
6677 TypeOfType(*this, tofType, Canonical, Kind);
6678 Types.push_back(tot);
6679 return QualType(tot, 0);
6680}
6681
6682/// getReferenceQualifiedType - Given an expr, will return the type for
6683/// that expression, as in [dcl.type.simple]p4 but without taking id-expressions
6684/// and class member access into account.
6686 // C++11 [dcl.type.simple]p4:
6687 // [...]
6688 QualType T = E->getType();
6689 switch (E->getValueKind()) {
6690 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
6691 // type of e;
6692 case VK_XValue:
6693 return getRValueReferenceType(T);
6694 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
6695 // type of e;
6696 case VK_LValue:
6697 return getLValueReferenceType(T);
6698 // - otherwise, decltype(e) is the type of e.
6699 case VK_PRValue:
6700 return T;
6701 }
6702 llvm_unreachable("Unknown value kind");
6703}
6704
6705/// Unlike many "get<Type>" functions, we don't unique DecltypeType
6706/// nodes. This would never be helpful, since each such type has its own
6707/// expression, and would not give a significant memory saving, since there
6708/// is an Expr tree under each such type.
6710 // C++11 [temp.type]p2:
6711 // If an expression e involves a template parameter, decltype(e) denotes a
6712 // unique dependent type. Two such decltype-specifiers refer to the same
6713 // type only if their expressions are equivalent (14.5.6.1).
6714 QualType CanonType;
6715 if (!E->isInstantiationDependent()) {
6716 CanonType = getCanonicalType(UnderlyingType);
6717 } else if (!UnderlyingType.isNull()) {
6718 CanonType = getDecltypeType(E, QualType());
6719 } else {
6720 llvm::FoldingSetNodeID ID;
6721 DependentDecltypeType::Profile(ID, *this, E);
6722
6723 void *InsertPos = nullptr;
6724 if (DependentDecltypeType *Canon =
6725 DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos))
6726 return QualType(Canon, 0);
6727
6728 // Build a new, canonical decltype(expr) type.
6729 auto *DT =
6730 new (*this, alignof(DependentDecltypeType)) DependentDecltypeType(E);
6731 DependentDecltypeTypes.InsertNode(DT, InsertPos);
6732 Types.push_back(DT);
6733 return QualType(DT, 0);
6734 }
6735 auto *DT = new (*this, alignof(DecltypeType))
6736 DecltypeType(E, UnderlyingType, CanonType);
6737 Types.push_back(DT);
6738 return QualType(DT, 0);
6739}
6740
6742 bool FullySubstituted,
6743 ArrayRef<QualType> Expansions,
6744 UnsignedOrNone Index) const {
6745 QualType Canonical;
6746 if (FullySubstituted && Index) {
6747 Canonical = getCanonicalType(Expansions[*Index]);
6748 } else {
6749 llvm::FoldingSetNodeID ID;
6750 PackIndexingType::Profile(ID, *this, Pattern.getCanonicalType(), IndexExpr,
6751 FullySubstituted, Expansions);
6752 void *InsertPos = nullptr;
6753 PackIndexingType *Canon =
6754 DependentPackIndexingTypes.FindNodeOrInsertPos(ID, InsertPos);
6755 if (!Canon) {
6756 void *Mem = Allocate(
6757 PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
6759 Canon =
6760 new (Mem) PackIndexingType(QualType(), Pattern.getCanonicalType(),
6761 IndexExpr, FullySubstituted, Expansions);
6762 DependentPackIndexingTypes.InsertNode(Canon, InsertPos);
6763 }
6764 Canonical = QualType(Canon, 0);
6765 }
6766
6767 void *Mem =
6768 Allocate(PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
6770 auto *T = new (Mem) PackIndexingType(Canonical, Pattern, IndexExpr,
6771 FullySubstituted, Expansions);
6772 Types.push_back(T);
6773 return QualType(T, 0);
6774}
6775
6776/// getUnaryTransformationType - We don't unique these, since the memory
6777/// savings are minimal and these are rare.
6780 UnaryTransformType::UTTKind Kind) const {
6781
6782 llvm::FoldingSetNodeID ID;
6783 UnaryTransformType::Profile(ID, BaseType, UnderlyingType, Kind);
6784
6785 void *InsertPos = nullptr;
6786 if (UnaryTransformType *UT =
6787 UnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos))
6788 return QualType(UT, 0);
6789
6790 QualType CanonType;
6791 if (!BaseType->isDependentType()) {
6792 CanonType = UnderlyingType.getCanonicalType();
6793 } else {
6794 assert(UnderlyingType.isNull() || BaseType == UnderlyingType);
6795 UnderlyingType = QualType();
6796 if (QualType CanonBase = BaseType.getCanonicalType();
6797 BaseType != CanonBase) {
6798 CanonType = getUnaryTransformType(CanonBase, QualType(), Kind);
6799 assert(CanonType.isCanonical());
6800
6801 // Find the insertion position again.
6802 [[maybe_unused]] UnaryTransformType *UT =
6803 UnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
6804 assert(!UT && "broken canonicalization");
6805 }
6806 }
6807
6808 auto *UT = new (*this, alignof(UnaryTransformType))
6809 UnaryTransformType(BaseType, UnderlyingType, Kind, CanonType);
6810 UnaryTransformTypes.InsertNode(UT, InsertPos);
6811 Types.push_back(UT);
6812 return QualType(UT, 0);
6813}
6814
6815/// getAutoType - Return the uniqued reference to the 'auto' type which has been
6816/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
6817/// canonical deduced-but-dependent 'auto' type.
6821 TemplateDecl *TypeConstraintConcept,
6822 ArrayRef<TemplateArgument> TypeConstraintArgs) const {
6824 !TypeConstraintConcept) {
6825 assert(DeducedAsType.isNull() && "");
6826 assert(TypeConstraintArgs.empty() && "");
6827 return getAutoDeductType();
6828 }
6829
6830 // Look in the folding set for an existing type.
6831 llvm::FoldingSetNodeID ID;
6832 AutoType::Profile(ID, *this, DK, DeducedAsType, Keyword,
6833 TypeConstraintConcept, TypeConstraintArgs);
6834 if (auto const AT_iter = AutoTypes.find(ID); AT_iter != AutoTypes.end())
6835 return QualType(AT_iter->getSecond(), 0);
6836
6837 if (DK == DeducedKind::Deduced) {
6838 assert(!DeducedAsType.isNull() && "deduced type must be provided");
6839 } else {
6840 assert(DeducedAsType.isNull() && "deduced type must not be provided");
6841 if (TypeConstraintConcept) {
6842 bool AnyNonCanonArgs = false;
6843 auto *CanonicalConcept =
6844 cast<TemplateDecl>(TypeConstraintConcept->getCanonicalDecl());
6845 auto CanonicalConceptArgs = ::getCanonicalTemplateArguments(
6846 *this, TypeConstraintArgs, AnyNonCanonArgs);
6847 if (TypeConstraintConcept != CanonicalConcept || AnyNonCanonArgs)
6848 DeducedAsType = getAutoType(DK, QualType(), Keyword, CanonicalConcept,
6849 CanonicalConceptArgs);
6850 }
6851 }
6852
6853 void *Mem = Allocate(sizeof(AutoType) +
6854 sizeof(TemplateArgument) * TypeConstraintArgs.size(),
6855 alignof(AutoType));
6856 auto *AT = new (Mem) AutoType(DK, DeducedAsType, Keyword,
6857 TypeConstraintConcept, TypeConstraintArgs);
6858#ifndef NDEBUG
6859 llvm::FoldingSetNodeID InsertedID;
6860 AT->Profile(InsertedID, *this);
6861 assert(InsertedID == ID && "ID does not match");
6862#endif
6863 Types.push_back(AT);
6864 AutoTypes.try_emplace(ID, AT);
6865 return QualType(AT, 0);
6866}
6867
6870
6871 // Remove a type-constraint from a top-level auto or decltype(auto).
6872 if (auto *AT = CanonT->getAs<AutoType>()) {
6873 if (!AT->isConstrained())
6874 return T;
6875 return getQualifiedType(
6876 getAutoType(AT->getDeducedKind(), QualType(), AT->getKeyword()),
6877 T.getQualifiers());
6878 }
6879
6880 // FIXME: We only support constrained auto at the top level in the type of a
6881 // non-type template parameter at the moment. Once we lift that restriction,
6882 // we'll need to recursively build types containing auto here.
6883 assert(!CanonT->getContainedAutoType() ||
6884 !CanonT->getContainedAutoType()->isConstrained());
6885 return T;
6886}
6887
6888/// Return the uniqued reference to the deduced template specialization type
6889/// which has been deduced to the given type, or to the canonical undeduced
6890/// such type, or the canonical deduced-but-dependent such type.
6893 TemplateName Template) const {
6894 // DeducedAsPack only ever occurs for lambda init-capture pack, which always
6895 // use AutoType.
6896 assert(DK != DeducedKind::DeducedAsPack &&
6897 "unexpected DeducedAsPack for DeducedTemplateSpecializationType");
6898
6899 // Look in the folding set for an existing type.
6900 void *InsertPos = nullptr;
6901 llvm::FoldingSetNodeID ID;
6902 DeducedTemplateSpecializationType::Profile(ID, DK, DeducedAsType, Keyword,
6903 Template);
6904 if (DeducedTemplateSpecializationType *DTST =
6905 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
6906 return QualType(DTST, 0);
6907
6908 if (DK == DeducedKind::Deduced) {
6909 assert(!DeducedAsType.isNull() && "deduced type must be provided");
6910 } else {
6911 assert(DeducedAsType.isNull() && "deduced type must not be provided");
6912 TemplateName CanonTemplateName = getCanonicalTemplateName(Template);
6913 // FIXME: Can this be formed from a DependentTemplateName, such that the
6914 // keyword should be part of the canonical type?
6916 Template != CanonTemplateName) {
6918 DK, QualType(), ElaboratedTypeKeyword::None, CanonTemplateName);
6919 // Find the insertion position again.
6920 [[maybe_unused]] DeducedTemplateSpecializationType *DTST =
6921 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
6922 assert(!DTST && "broken canonicalization");
6923 }
6924 }
6925
6926 auto *DTST = new (*this, alignof(DeducedTemplateSpecializationType))
6927 DeducedTemplateSpecializationType(DK, DeducedAsType, Keyword, Template);
6928
6929#ifndef NDEBUG
6930 llvm::FoldingSetNodeID TempID;
6931 DTST->Profile(TempID);
6932 assert(ID == TempID && "ID does not match");
6933#endif
6934 Types.push_back(DTST);
6935 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
6936 return QualType(DTST, 0);
6937}
6938
6939/// getAtomicType - Return the uniqued reference to the atomic type for
6940/// the given value type.
6942 // Unique pointers, to guarantee there is only one pointer of a particular
6943 // structure.
6944 llvm::FoldingSetNodeID ID;
6945 AtomicType::Profile(ID, T);
6946
6947 void *InsertPos = nullptr;
6948 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
6949 return QualType(AT, 0);
6950
6951 // If the atomic value type isn't canonical, this won't be a canonical type
6952 // either, so fill in the canonical type field.
6953 QualType Canonical;
6954 if (!T.isCanonical()) {
6955 Canonical = getAtomicType(getCanonicalType(T));
6956
6957 // Get the new insert position for the node we care about.
6958 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
6959 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
6960 }
6961 auto *New = new (*this, alignof(AtomicType)) AtomicType(T, Canonical);
6962 Types.push_back(New);
6963 AtomicTypes.InsertNode(New, InsertPos);
6964 return QualType(New, 0);
6965}
6966
6967/// getAutoDeductType - Get type pattern for deducing against 'auto'.
6969 if (AutoDeductTy.isNull())
6970 AutoDeductTy = QualType(new (*this, alignof(AutoType))
6971 AutoType(DeducedKind::Undeduced, QualType(),
6973 /*TypeConstraintConcept=*/nullptr,
6974 /*TypeConstraintArgs=*/{}),
6975 0);
6976 return AutoDeductTy;
6977}
6978
6979/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
6981 if (AutoRRefDeductTy.isNull())
6983 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
6984 return AutoRRefDeductTy;
6985}
6986
6987/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
6988/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
6989/// needs to agree with the definition in <stddef.h>.
6993
6995 return getFromTargetType(Target->getSizeType());
6996}
6997
6998/// Return the unique signed counterpart of the integer type
6999/// corresponding to size_t.
7003
7004/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
7005/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
7009
7010/// Return the unique unsigned counterpart of "ptrdiff_t"
7011/// integer type. The standard (C11 7.21.6.1p7) refers to this type
7012/// in the definition of %tu format specifier.
7014 return getFromTargetType(Target->getUnsignedPtrDiffType(LangAS::Default));
7015}
7016
7017/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
7019 return getFromTargetType(Target->getIntMaxType());
7020}
7021
7022/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
7024 return getFromTargetType(Target->getUIntMaxType());
7025}
7026
7027/// getSignedWCharType - Return the type of "signed wchar_t".
7028/// Used when in C++, as a GCC extension.
7030 // FIXME: derive from "Target" ?
7031 return WCharTy;
7032}
7033
7034/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
7035/// Used when in C++, as a GCC extension.
7037 // FIXME: derive from "Target" ?
7038 return UnsignedIntTy;
7039}
7040
7042 return getFromTargetType(Target->getIntPtrType());
7043}
7044
7048
7049/// Return the unique type for "pid_t" defined in
7050/// <sys/types.h>. We need this to compute the correct type for vfork().
7052 return getFromTargetType(Target->getProcessIDType());
7053}
7054
7055//===----------------------------------------------------------------------===//
7056// Type Operators
7057//===----------------------------------------------------------------------===//
7058
7060 // Push qualifiers into arrays, and then discard any remaining
7061 // qualifiers.
7062 T = getCanonicalType(T);
7064 const Type *Ty = T.getTypePtr();
7068 } else if (isa<ArrayType>(Ty)) {
7070 } else if (isa<FunctionType>(Ty)) {
7071 Result = getPointerType(QualType(Ty, 0));
7072 } else {
7073 Result = QualType(Ty, 0);
7074 }
7075
7077}
7078
7080 Qualifiers &quals) const {
7081 SplitQualType splitType = type.getSplitUnqualifiedType();
7082
7083 // FIXME: getSplitUnqualifiedType() actually walks all the way to
7084 // the unqualified desugared type and then drops it on the floor.
7085 // We then have to strip that sugar back off with
7086 // getUnqualifiedDesugaredType(), which is silly.
7087 const auto *AT =
7088 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
7089
7090 // If we don't have an array, just use the results in splitType.
7091 if (!AT) {
7092 quals = splitType.Quals;
7093 return QualType(splitType.Ty, 0);
7094 }
7095
7096 // Otherwise, recurse on the array's element type.
7097 QualType elementType = AT->getElementType();
7098 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
7099
7100 // If that didn't change the element type, AT has no qualifiers, so we
7101 // can just use the results in splitType.
7102 if (elementType == unqualElementType) {
7103 assert(quals.empty()); // from the recursive call
7104 quals = splitType.Quals;
7105 return QualType(splitType.Ty, 0);
7106 }
7107
7108 // Otherwise, add in the qualifiers from the outermost type, then
7109 // build the type back up.
7110 quals.addConsistentQualifiers(splitType.Quals);
7111
7112 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
7113 return getConstantArrayType(unqualElementType, CAT->getSize(),
7114 CAT->getSizeExpr(), CAT->getSizeModifier(), 0);
7115 }
7116
7117 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
7118 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
7119 }
7120
7121 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
7122 return getVariableArrayType(unqualElementType, VAT->getSizeExpr(),
7123 VAT->getSizeModifier(),
7124 VAT->getIndexTypeCVRQualifiers());
7125 }
7126
7127 const auto *DSAT = cast<DependentSizedArrayType>(AT);
7128 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
7129 DSAT->getSizeModifier(), 0);
7130}
7131
7132/// Attempt to unwrap two types that may both be array types with the same bound
7133/// (or both be array types of unknown bound) for the purpose of comparing the
7134/// cv-decomposition of two types per C++ [conv.qual].
7135///
7136/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
7137/// C++20 [conv.qual], if permitted by the current language mode.
7139 bool AllowPiMismatch) const {
7140 while (true) {
7141 auto *AT1 = getAsArrayType(T1);
7142 if (!AT1)
7143 return;
7144
7145 auto *AT2 = getAsArrayType(T2);
7146 if (!AT2)
7147 return;
7148
7149 // If we don't have two array types with the same constant bound nor two
7150 // incomplete array types, we've unwrapped everything we can.
7151 // C++20 also permits one type to be a constant array type and the other
7152 // to be an incomplete array type.
7153 // FIXME: Consider also unwrapping array of unknown bound and VLA.
7154 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
7155 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
7156 if (!((CAT2 && CAT1->getSize() == CAT2->getSize()) ||
7157 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
7159 return;
7160 } else if (isa<IncompleteArrayType>(AT1)) {
7161 if (!(isa<IncompleteArrayType>(AT2) ||
7162 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
7164 return;
7165 } else {
7166 return;
7167 }
7168
7169 T1 = AT1->getElementType();
7170 T2 = AT2->getElementType();
7171 }
7172}
7173
7174/// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
7175///
7176/// If T1 and T2 are both pointer types of the same kind, or both array types
7177/// with the same bound, unwraps layers from T1 and T2 until a pointer type is
7178/// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
7179///
7180/// This function will typically be called in a loop that successively
7181/// "unwraps" pointer and pointer-to-member types to compare them at each
7182/// level.
7183///
7184/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
7185/// C++20 [conv.qual], if permitted by the current language mode.
7186///
7187/// \return \c true if a pointer type was unwrapped, \c false if we reached a
7188/// pair of types that can't be unwrapped further.
7190 bool AllowPiMismatch) const {
7191 UnwrapSimilarArrayTypes(T1, T2, AllowPiMismatch);
7192
7193 const auto *T1PtrType = T1->getAs<PointerType>();
7194 const auto *T2PtrType = T2->getAs<PointerType>();
7195 if (T1PtrType && T2PtrType) {
7196 T1 = T1PtrType->getPointeeType();
7197 T2 = T2PtrType->getPointeeType();
7198 return true;
7199 }
7200
7201 if (const auto *T1MPType = T1->getAsCanonical<MemberPointerType>(),
7202 *T2MPType = T2->getAsCanonical<MemberPointerType>();
7203 T1MPType && T2MPType) {
7204 // Compare the qualifiers of the canonical type, as the non-canonical type
7205 // may have qualifiers pointing to a base or derived class.
7206 if (T1MPType->getQualifier() != T2MPType->getQualifier())
7207 return false;
7208 // Get the pointee types of the non-canonical type, in order to preserve
7209 // their sugar.
7210 T1 = T1->getAs<MemberPointerType>()->getPointeeType();
7211 T2 = T2->getAs<MemberPointerType>()->getPointeeType();
7212 return true;
7213 }
7214
7215 if (getLangOpts().ObjC) {
7216 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
7217 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
7218 if (T1OPType && T2OPType) {
7219 T1 = T1OPType->getPointeeType();
7220 T2 = T2OPType->getPointeeType();
7221 return true;
7222 }
7223 }
7224
7225 // FIXME: Block pointers, too?
7226
7227 return false;
7228}
7229
7231 while (true) {
7232 Qualifiers Quals;
7233 T1 = getUnqualifiedArrayType(T1, Quals);
7234 T2 = getUnqualifiedArrayType(T2, Quals);
7235 if (hasSameType(T1, T2))
7236 return true;
7237 if (!UnwrapSimilarTypes(T1, T2))
7238 return false;
7239 }
7240}
7241
7243 while (true) {
7244 Qualifiers Quals1, Quals2;
7245 T1 = getUnqualifiedArrayType(T1, Quals1);
7246 T2 = getUnqualifiedArrayType(T2, Quals2);
7247
7248 Quals1.removeCVRQualifiers();
7249 Quals2.removeCVRQualifiers();
7250 if (Quals1 != Quals2)
7251 return false;
7252
7253 if (hasSameType(T1, T2))
7254 return true;
7255
7256 if (!UnwrapSimilarTypes(T1, T2, /*AllowPiMismatch*/ false))
7257 return false;
7258 }
7259}
7260
7263 SourceLocation NameLoc) const {
7264 switch (Name.getKind()) {
7267 // DNInfo work in progress: CHECKME: what about DNLoc?
7269 NameLoc);
7270
7273 // DNInfo work in progress: CHECKME: what about DNLoc?
7274 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
7275 }
7276
7279 return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
7280 }
7281
7285 DeclarationName DName;
7286 if (const IdentifierInfo *II = TN.getIdentifier()) {
7287 DName = DeclarationNames.getIdentifier(II);
7288 return DeclarationNameInfo(DName, NameLoc);
7289 } else {
7290 DName = DeclarationNames.getCXXOperatorName(TN.getOperator());
7291 // DNInfo work in progress: FIXME: source locations?
7292 DeclarationNameLoc DNLoc =
7294 return DeclarationNameInfo(DName, NameLoc, DNLoc);
7295 }
7296 }
7297
7301 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
7302 NameLoc);
7303 }
7304
7309 NameLoc);
7310 }
7313 NameLoc);
7316 return getNameForTemplate(DTS->getUnderlying(), NameLoc);
7317 }
7318 }
7319
7320 llvm_unreachable("bad template name kind!");
7321}
7322
7323const TemplateArgument *
7325 auto handleParam = [](auto *TP) -> const TemplateArgument * {
7326 if (!TP->hasDefaultArgument())
7327 return nullptr;
7328 return &TP->getDefaultArgument().getArgument();
7329 };
7330 switch (P->getKind()) {
7331 case NamedDecl::TemplateTypeParm:
7332 return handleParam(cast<TemplateTypeParmDecl>(P));
7333 case NamedDecl::NonTypeTemplateParm:
7334 return handleParam(cast<NonTypeTemplateParmDecl>(P));
7335 case NamedDecl::TemplateTemplateParm:
7336 return handleParam(cast<TemplateTemplateParmDecl>(P));
7337 default:
7338 llvm_unreachable("Unexpected template parameter kind");
7339 }
7340}
7341
7343 bool IgnoreDeduced) const {
7344 while (std::optional<TemplateName> UnderlyingOrNone =
7345 Name.desugar(IgnoreDeduced))
7346 Name = *UnderlyingOrNone;
7347
7348 switch (Name.getKind()) {
7351 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template))
7353
7354 // The canonical template name is the canonical template declaration.
7355 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
7356 }
7357
7359 // An assumed template is just a name, so it is already canonical.
7360 return Name;
7361
7363 llvm_unreachable("cannot canonicalize overloaded template");
7364
7367 assert(DTN && "Non-dependent template names must refer to template decls.");
7368 NestedNameSpecifier Qualifier = DTN->getQualifier();
7369 NestedNameSpecifier CanonQualifier = Qualifier.getCanonical();
7370 if (Qualifier != CanonQualifier || !DTN->hasTemplateKeyword())
7371 return getDependentTemplateName({CanonQualifier, DTN->getName(),
7372 /*HasTemplateKeyword=*/true});
7373 return Name;
7374 }
7375
7379 TemplateArgument canonArgPack =
7382 canonArgPack, subst->getAssociatedDecl()->getCanonicalDecl(),
7383 subst->getIndex(), subst->getFinal());
7384 }
7386 assert(IgnoreDeduced == false);
7388 DefaultArguments DefArgs = DTS->getDefaultArguments();
7389 TemplateName Underlying = DTS->getUnderlying();
7390
7391 TemplateName CanonUnderlying =
7392 getCanonicalTemplateName(Underlying, /*IgnoreDeduced=*/true);
7393 bool NonCanonical = CanonUnderlying != Underlying;
7394 auto CanonArgs =
7395 getCanonicalTemplateArguments(*this, DefArgs.Args, NonCanonical);
7396
7397 ArrayRef<NamedDecl *> Params =
7398 CanonUnderlying.getAsTemplateDecl()->getTemplateParameters()->asArray();
7399 assert(CanonArgs.size() <= Params.size());
7400 // A deduced template name which deduces the same default arguments already
7401 // declared in the underlying template is the same template as the
7402 // underlying template. We need need to note any arguments which differ from
7403 // the corresponding declaration. If any argument differs, we must build a
7404 // deduced template name.
7405 for (int I = CanonArgs.size() - 1; I >= 0; --I) {
7407 if (!A)
7408 break;
7409 auto CanonParamDefArg = getCanonicalTemplateArgument(*A);
7410 TemplateArgument &CanonDefArg = CanonArgs[I];
7411 if (CanonDefArg.structurallyEquals(CanonParamDefArg))
7412 continue;
7413 // Keep popping from the back any deault arguments which are the same.
7414 if (I == int(CanonArgs.size() - 1))
7415 CanonArgs.pop_back();
7416 NonCanonical = true;
7417 }
7418 return NonCanonical ? getDeducedTemplateName(
7419 CanonUnderlying,
7420 /*DefaultArgs=*/{DefArgs.StartPos, CanonArgs})
7421 : Name;
7422 }
7426 llvm_unreachable("always sugar node");
7427 }
7428
7429 llvm_unreachable("bad template name!");
7430}
7431
7433 const TemplateName &Y,
7434 bool IgnoreDeduced) const {
7435 return getCanonicalTemplateName(X, IgnoreDeduced) ==
7436 getCanonicalTemplateName(Y, IgnoreDeduced);
7437}
7438
7440 const AssociatedConstraint &ACX, const AssociatedConstraint &ACY) const {
7441 if (ACX.ArgPackSubstIndex != ACY.ArgPackSubstIndex)
7442 return false;
7444 return false;
7445 return true;
7446}
7447
7448bool ASTContext::isSameConstraintExpr(const Expr *XCE, const Expr *YCE) const {
7449 if (!XCE != !YCE)
7450 return false;
7451
7452 if (!XCE)
7453 return true;
7454
7455 llvm::FoldingSetNodeID XCEID, YCEID;
7456 XCE->Profile(XCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7457 YCE->Profile(YCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7458 return XCEID == YCEID;
7459}
7460
7462 const TypeConstraint *YTC) const {
7463 if (!XTC != !YTC)
7464 return false;
7465
7466 if (!XTC)
7467 return true;
7468
7469 auto *NCX = XTC->getNamedConcept();
7470 auto *NCY = YTC->getNamedConcept();
7471 if (!NCX || !NCY || !isSameEntity(NCX, NCY))
7472 return false;
7475 return false;
7477 if (XTC->getConceptReference()
7479 ->NumTemplateArgs !=
7481 return false;
7482
7483 // Compare slowly by profiling.
7484 //
7485 // We couldn't compare the profiling result for the template
7486 // args here. Consider the following example in different modules:
7487 //
7488 // template <__integer_like _Tp, C<_Tp> Sentinel>
7489 // constexpr _Tp operator()(_Tp &&__t, Sentinel &&last) const {
7490 // return __t;
7491 // }
7492 //
7493 // When we compare the profiling result for `C<_Tp>` in different
7494 // modules, it will compare the type of `_Tp` in different modules.
7495 // However, the type of `_Tp` in different modules refer to different
7496 // types here naturally. So we couldn't compare the profiling result
7497 // for the template args directly.
7500}
7501
7503 const NamedDecl *Y) const {
7504 if (X->getKind() != Y->getKind())
7505 return false;
7506
7507 if (auto *TX = dyn_cast<TemplateTypeParmDecl>(X)) {
7508 auto *TY = cast<TemplateTypeParmDecl>(Y);
7509 if (TX->isParameterPack() != TY->isParameterPack())
7510 return false;
7511 if (TX->hasTypeConstraint() != TY->hasTypeConstraint())
7512 return false;
7513 return isSameTypeConstraint(TX->getTypeConstraint(),
7514 TY->getTypeConstraint());
7515 }
7516
7517 if (auto *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
7518 auto *TY = cast<NonTypeTemplateParmDecl>(Y);
7519 return TX->isParameterPack() == TY->isParameterPack() &&
7520 TX->getASTContext().hasSameType(TX->getType(), TY->getType()) &&
7521 isSameConstraintExpr(TX->getPlaceholderTypeConstraint(),
7522 TY->getPlaceholderTypeConstraint());
7523 }
7524
7526 auto *TY = cast<TemplateTemplateParmDecl>(Y);
7527 return TX->isParameterPack() == TY->isParameterPack() &&
7528 isSameTemplateParameterList(TX->getTemplateParameters(),
7529 TY->getTemplateParameters());
7530}
7531
7533 const TemplateParameterList *X, const TemplateParameterList *Y) const {
7534 if (X->size() != Y->size())
7535 return false;
7536
7537 for (unsigned I = 0, N = X->size(); I != N; ++I)
7538 if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I)))
7539 return false;
7540
7541 return isSameConstraintExpr(X->getRequiresClause(), Y->getRequiresClause());
7542}
7543
7545 const NamedDecl *Y) const {
7546 // If the type parameter isn't the same already, we don't need to check the
7547 // default argument further.
7548 if (!isSameTemplateParameter(X, Y))
7549 return false;
7550
7551 if (auto *TTPX = dyn_cast<TemplateTypeParmDecl>(X)) {
7552 auto *TTPY = cast<TemplateTypeParmDecl>(Y);
7553 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7554 return false;
7555
7556 return hasSameType(TTPX->getDefaultArgument().getArgument().getAsType(),
7557 TTPY->getDefaultArgument().getArgument().getAsType());
7558 }
7559
7560 if (auto *NTTPX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
7561 auto *NTTPY = cast<NonTypeTemplateParmDecl>(Y);
7562 if (!NTTPX->hasDefaultArgument() || !NTTPY->hasDefaultArgument())
7563 return false;
7564
7565 Expr *DefaultArgumentX =
7566 NTTPX->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7567 Expr *DefaultArgumentY =
7568 NTTPY->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7569 llvm::FoldingSetNodeID XID, YID;
7570 DefaultArgumentX->Profile(XID, *this, /*Canonical=*/true);
7571 DefaultArgumentY->Profile(YID, *this, /*Canonical=*/true);
7572 return XID == YID;
7573 }
7574
7575 auto *TTPX = cast<TemplateTemplateParmDecl>(X);
7576 auto *TTPY = cast<TemplateTemplateParmDecl>(Y);
7577
7578 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7579 return false;
7580
7581 const TemplateArgument &TAX = TTPX->getDefaultArgument().getArgument();
7582 const TemplateArgument &TAY = TTPY->getDefaultArgument().getArgument();
7583 return hasSameTemplateName(TAX.getAsTemplate(), TAY.getAsTemplate());
7584}
7585
7587 const NestedNameSpecifier Y) {
7588 if (X == Y)
7589 return true;
7590 if (!X || !Y)
7591 return false;
7592
7593 auto Kind = X.getKind();
7594 if (Kind != Y.getKind())
7595 return false;
7596
7597 // FIXME: For namespaces and types, we're permitted to check that the entity
7598 // is named via the same tokens. We should probably do so.
7599 switch (Kind) {
7601 auto [NamespaceX, PrefixX] = X.getAsNamespaceAndPrefix();
7602 auto [NamespaceY, PrefixY] = Y.getAsNamespaceAndPrefix();
7603 if (!declaresSameEntity(NamespaceX->getNamespace(),
7604 NamespaceY->getNamespace()))
7605 return false;
7606 return isSameQualifier(PrefixX, PrefixY);
7607 }
7609 const auto *TX = X.getAsType(), *TY = Y.getAsType();
7610 if (TX->getCanonicalTypeInternal() != TY->getCanonicalTypeInternal())
7611 return false;
7612 return isSameQualifier(TX->getPrefix(), TY->getPrefix());
7613 }
7617 return true;
7618 }
7619 llvm_unreachable("unhandled qualifier kind");
7620}
7621
7622static bool hasSameCudaAttrs(const FunctionDecl *A, const FunctionDecl *B) {
7623 if (!A->getASTContext().getLangOpts().CUDA)
7624 return true; // Target attributes are overloadable in CUDA compilation only.
7625 if (A->hasAttr<CUDADeviceAttr>() != B->hasAttr<CUDADeviceAttr>())
7626 return false;
7627 if (A->hasAttr<CUDADeviceAttr>() && B->hasAttr<CUDADeviceAttr>())
7628 return A->hasAttr<CUDAHostAttr>() == B->hasAttr<CUDAHostAttr>();
7629 return true; // unattributed and __host__ functions are the same.
7630}
7631
7632/// Determine whether the attributes we can overload on are identical for A and
7633/// B. Will ignore any overloadable attrs represented in the type of A and B.
7635 const FunctionDecl *B) {
7636 // Note that pass_object_size attributes are represented in the function's
7637 // ExtParameterInfo, so we don't need to check them here.
7638
7639 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
7640 auto AEnableIfAttrs = A->specific_attrs<EnableIfAttr>();
7641 auto BEnableIfAttrs = B->specific_attrs<EnableIfAttr>();
7642
7643 for (auto Pair : zip_longest(AEnableIfAttrs, BEnableIfAttrs)) {
7644 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
7645 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
7646
7647 // Return false if the number of enable_if attributes is different.
7648 if (!Cand1A || !Cand2A)
7649 return false;
7650
7651 Cand1ID.clear();
7652 Cand2ID.clear();
7653
7654 (*Cand1A)->getCond()->Profile(Cand1ID, A->getASTContext(), true);
7655 (*Cand2A)->getCond()->Profile(Cand2ID, B->getASTContext(), true);
7656
7657 // Return false if any of the enable_if expressions of A and B are
7658 // different.
7659 if (Cand1ID != Cand2ID)
7660 return false;
7661 }
7662 return hasSameCudaAttrs(A, B);
7663}
7664
7665bool ASTContext::isSameEntity(const NamedDecl *X, const NamedDecl *Y) const {
7666 // Caution: this function is called by the AST reader during deserialization,
7667 // so it cannot rely on AST invariants being met. Non-trivial accessors
7668 // should be avoided, along with any traversal of redeclaration chains.
7669
7670 if (X == Y)
7671 return true;
7672
7673 if (X->getDeclName() != Y->getDeclName())
7674 return false;
7675
7676 // Must be in the same context.
7677 //
7678 // Note that we can't use DeclContext::Equals here, because the DeclContexts
7679 // could be two different declarations of the same function. (We will fix the
7680 // semantic DC to refer to the primary definition after merging.)
7681 if (!declaresSameEntity(cast<Decl>(X->getDeclContext()->getRedeclContext()),
7683 return false;
7684
7685 // If either X or Y are local to the owning module, they are only possible to
7686 // be the same entity if they are in the same module.
7687 if (X->isModuleLocal() || Y->isModuleLocal())
7688 if (!isInSameModule(X->getOwningModule(), Y->getOwningModule()))
7689 return false;
7690
7691 // Two typedefs refer to the same entity if they have the same underlying
7692 // type.
7693 if (const auto *TypedefX = dyn_cast<TypedefNameDecl>(X))
7694 if (const auto *TypedefY = dyn_cast<TypedefNameDecl>(Y))
7695 return hasSameType(TypedefX->getUnderlyingType(),
7696 TypedefY->getUnderlyingType());
7697
7698 // Must have the same kind.
7699 if (X->getKind() != Y->getKind())
7700 return false;
7701
7702 // Objective-C classes and protocols with the same name always match.
7704 return true;
7705
7707 // No need to handle these here: we merge them when adding them to the
7708 // template.
7709 return false;
7710 }
7711
7712 // Compatible tags match.
7713 if (const auto *TagX = dyn_cast<TagDecl>(X)) {
7714 const auto *TagY = cast<TagDecl>(Y);
7715 return (TagX->getTagKind() == TagY->getTagKind()) ||
7716 ((TagX->getTagKind() == TagTypeKind::Struct ||
7717 TagX->getTagKind() == TagTypeKind::Class ||
7718 TagX->getTagKind() == TagTypeKind::Interface) &&
7719 (TagY->getTagKind() == TagTypeKind::Struct ||
7720 TagY->getTagKind() == TagTypeKind::Class ||
7721 TagY->getTagKind() == TagTypeKind::Interface));
7722 }
7723
7724 // Functions with the same type and linkage match.
7725 // FIXME: This needs to cope with merging of prototyped/non-prototyped
7726 // functions, etc.
7727 if (const auto *FuncX = dyn_cast<FunctionDecl>(X)) {
7728 const auto *FuncY = cast<FunctionDecl>(Y);
7729 if (const auto *CtorX = dyn_cast<CXXConstructorDecl>(X)) {
7730 const auto *CtorY = cast<CXXConstructorDecl>(Y);
7731 if (CtorX->getInheritedConstructor() &&
7732 !isSameEntity(CtorX->getInheritedConstructor().getConstructor(),
7733 CtorY->getInheritedConstructor().getConstructor()))
7734 return false;
7735 }
7736
7737 if (FuncX->isMultiVersion() != FuncY->isMultiVersion())
7738 return false;
7739
7740 // Multiversioned functions with different feature strings are represented
7741 // as separate declarations.
7742 if (FuncX->isMultiVersion()) {
7743 const auto *TAX = FuncX->getAttr<TargetAttr>();
7744 const auto *TAY = FuncY->getAttr<TargetAttr>();
7745 assert(TAX && TAY && "Multiversion Function without target attribute");
7746
7747 if (TAX->getFeaturesStr() != TAY->getFeaturesStr())
7748 return false;
7749 }
7750
7751 // Per C++20 [temp.over.link]/4, friends in different classes are sometimes
7752 // not the same entity if they are constrained.
7753 if ((FuncX->isMemberLikeConstrainedFriend() ||
7754 FuncY->isMemberLikeConstrainedFriend()) &&
7755 !FuncX->getLexicalDeclContext()->Equals(
7756 FuncY->getLexicalDeclContext())) {
7757 return false;
7758 }
7759
7760 if (!isSameAssociatedConstraint(FuncX->getTrailingRequiresClause(),
7761 FuncY->getTrailingRequiresClause()))
7762 return false;
7763
7764 auto GetTypeAsWritten = [](const FunctionDecl *FD) {
7765 // Map to the first declaration that we've already merged into this one.
7766 // The TSI of redeclarations might not match (due to calling conventions
7767 // being inherited onto the type but not the TSI), but the TSI type of
7768 // the first declaration of the function should match across modules.
7769 FD = FD->getCanonicalDecl();
7770 return FD->getTypeSourceInfo() ? FD->getTypeSourceInfo()->getType()
7771 : FD->getType();
7772 };
7773 QualType XT = GetTypeAsWritten(FuncX), YT = GetTypeAsWritten(FuncY);
7774 if (!hasSameType(XT, YT)) {
7775 // We can get functions with different types on the redecl chain in C++17
7776 // if they have differing exception specifications and at least one of
7777 // the excpetion specs is unresolved.
7778 auto *XFPT = XT->getAs<FunctionProtoType>();
7779 auto *YFPT = YT->getAs<FunctionProtoType>();
7780 if (getLangOpts().CPlusPlus17 && XFPT && YFPT &&
7781 (isUnresolvedExceptionSpec(XFPT->getExceptionSpecType()) ||
7784 return true;
7785 return false;
7786 }
7787
7788 return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() &&
7789 hasSameOverloadableAttrs(FuncX, FuncY);
7790 }
7791
7792 // Variables with the same type and linkage match.
7793 if (const auto *VarX = dyn_cast<VarDecl>(X)) {
7794 const auto *VarY = cast<VarDecl>(Y);
7795 if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) {
7796 // During deserialization, we might compare variables before we load
7797 // their types. Assume the types will end up being the same.
7798 if (VarX->getType().isNull() || VarY->getType().isNull())
7799 return true;
7800
7801 if (hasSameType(VarX->getType(), VarY->getType()))
7802 return true;
7803
7804 // We can get decls with different types on the redecl chain. Eg.
7805 // template <typename T> struct S { static T Var[]; }; // #1
7806 // template <typename T> T S<T>::Var[sizeof(T)]; // #2
7807 // Only? happens when completing an incomplete array type. In this case
7808 // when comparing #1 and #2 we should go through their element type.
7809 const ArrayType *VarXTy = getAsArrayType(VarX->getType());
7810 const ArrayType *VarYTy = getAsArrayType(VarY->getType());
7811 if (!VarXTy || !VarYTy)
7812 return false;
7813 if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType())
7814 return hasSameType(VarXTy->getElementType(), VarYTy->getElementType());
7815 }
7816 return false;
7817 }
7818
7819 // Namespaces with the same name and inlinedness match.
7820 if (const auto *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
7821 const auto *NamespaceY = cast<NamespaceDecl>(Y);
7822 return NamespaceX->isInline() == NamespaceY->isInline();
7823 }
7824
7825 // Identical template names and kinds match if their template parameter lists
7826 // and patterns match.
7827 if (const auto *TemplateX = dyn_cast<TemplateDecl>(X)) {
7828 const auto *TemplateY = cast<TemplateDecl>(Y);
7829
7830 // ConceptDecl wouldn't be the same if their constraint expression differs.
7831 if (const auto *ConceptX = dyn_cast<ConceptDecl>(X)) {
7832 const auto *ConceptY = cast<ConceptDecl>(Y);
7833 if (!isSameConstraintExpr(ConceptX->getConstraintExpr(),
7834 ConceptY->getConstraintExpr()))
7835 return false;
7836 }
7837
7838 return isSameEntity(TemplateX->getTemplatedDecl(),
7839 TemplateY->getTemplatedDecl()) &&
7840 isSameTemplateParameterList(TemplateX->getTemplateParameters(),
7841 TemplateY->getTemplateParameters());
7842 }
7843
7844 // Fields with the same name and the same type match.
7845 if (const auto *FDX = dyn_cast<FieldDecl>(X)) {
7846 const auto *FDY = cast<FieldDecl>(Y);
7847 // FIXME: Also check the bitwidth is odr-equivalent, if any.
7848 return hasSameType(FDX->getType(), FDY->getType());
7849 }
7850
7851 // Indirect fields with the same target field match.
7852 if (const auto *IFDX = dyn_cast<IndirectFieldDecl>(X)) {
7853 const auto *IFDY = cast<IndirectFieldDecl>(Y);
7854 return IFDX->getAnonField()->getCanonicalDecl() ==
7855 IFDY->getAnonField()->getCanonicalDecl();
7856 }
7857
7858 // Enumerators with the same name match.
7860 // FIXME: Also check the value is odr-equivalent.
7861 return true;
7862
7863 // Using shadow declarations with the same target match.
7864 if (const auto *USX = dyn_cast<UsingShadowDecl>(X)) {
7865 const auto *USY = cast<UsingShadowDecl>(Y);
7866 return declaresSameEntity(USX->getTargetDecl(), USY->getTargetDecl());
7867 }
7868
7869 // Using declarations with the same qualifier match. (We already know that
7870 // the name matches.)
7871 if (const auto *UX = dyn_cast<UsingDecl>(X)) {
7872 const auto *UY = cast<UsingDecl>(Y);
7873 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7874 UX->hasTypename() == UY->hasTypename() &&
7875 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7876 }
7877 if (const auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) {
7878 const auto *UY = cast<UnresolvedUsingValueDecl>(Y);
7879 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7880 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7881 }
7882 if (const auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X)) {
7883 return isSameQualifier(
7884 UX->getQualifier(),
7885 cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier());
7886 }
7887
7888 // Using-pack declarations are only created by instantiation, and match if
7889 // they're instantiated from matching UnresolvedUsing...Decls.
7890 if (const auto *UX = dyn_cast<UsingPackDecl>(X)) {
7891 return declaresSameEntity(
7892 UX->getInstantiatedFromUsingDecl(),
7893 cast<UsingPackDecl>(Y)->getInstantiatedFromUsingDecl());
7894 }
7895
7896 // Namespace alias definitions with the same target match.
7897 if (const auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) {
7898 const auto *NAY = cast<NamespaceAliasDecl>(Y);
7899 return NAX->getNamespace()->Equals(NAY->getNamespace());
7900 }
7901
7902 return false;
7903}
7904
7907 switch (Arg.getKind()) {
7909 return Arg;
7910
7912 return TemplateArgument(Arg.getAsExpr(), /*IsCanonical=*/true,
7913 Arg.getIsDefaulted());
7914
7916 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
7918 Arg.getIsDefaulted());
7919 }
7920
7923 /*isNullPtr*/ true, Arg.getIsDefaulted());
7924
7927 Arg.getIsDefaulted());
7928
7930 return TemplateArgument(
7933
7936
7938 return TemplateArgument(*this,
7941
7944 /*isNullPtr*/ false, Arg.getIsDefaulted());
7945
7947 bool AnyNonCanonArgs = false;
7948 auto CanonArgs = ::getCanonicalTemplateArguments(
7949 *this, Arg.pack_elements(), AnyNonCanonArgs);
7950 if (!AnyNonCanonArgs)
7951 return Arg;
7953 const_cast<ASTContext &>(*this), CanonArgs);
7954 NewArg.setIsDefaulted(Arg.getIsDefaulted());
7955 return NewArg;
7956 }
7957 }
7958
7959 // Silence GCC warning
7960 llvm_unreachable("Unhandled template argument kind");
7961}
7962
7964 const TemplateArgument &Arg2) const {
7965 if (Arg1.getKind() != Arg2.getKind())
7966 return false;
7967
7968 switch (Arg1.getKind()) {
7970 llvm_unreachable("Comparing NULL template argument");
7971
7973 return hasSameType(Arg1.getAsType(), Arg2.getAsType());
7974
7976 return Arg1.getAsDecl()->getUnderlyingDecl()->getCanonicalDecl() ==
7978
7980 return hasSameType(Arg1.getNullPtrType(), Arg2.getNullPtrType());
7981
7986
7988 return llvm::APSInt::isSameValue(Arg1.getAsIntegral(),
7989 Arg2.getAsIntegral());
7990
7992 return Arg1.structurallyEquals(Arg2);
7993
7995 llvm::FoldingSetNodeID ID1, ID2;
7996 Arg1.getAsExpr()->Profile(ID1, *this, /*Canonical=*/true);
7997 Arg2.getAsExpr()->Profile(ID2, *this, /*Canonical=*/true);
7998 return ID1 == ID2;
7999 }
8000
8002 return llvm::equal(
8003 Arg1.getPackAsArray(), Arg2.getPackAsArray(),
8004 [&](const TemplateArgument &Arg1, const TemplateArgument &Arg2) {
8005 return isSameTemplateArgument(Arg1, Arg2);
8006 });
8007 }
8008
8009 llvm_unreachable("Unhandled template argument kind");
8010}
8011
8013 // Handle the non-qualified case efficiently.
8014 if (!T.hasLocalQualifiers()) {
8015 // Handle the common positive case fast.
8016 if (const auto *AT = dyn_cast<ArrayType>(T))
8017 return AT;
8018 }
8019
8020 // Handle the common negative case fast.
8021 if (!isa<ArrayType>(T.getCanonicalType()))
8022 return nullptr;
8023
8024 // Apply any qualifiers from the array type to the element type. This
8025 // implements C99 6.7.3p8: "If the specification of an array type includes
8026 // any type qualifiers, the element type is so qualified, not the array type."
8027
8028 // If we get here, we either have type qualifiers on the type, or we have
8029 // sugar such as a typedef in the way. If we have type qualifiers on the type
8030 // we must propagate them down into the element type.
8031
8032 SplitQualType split = T.getSplitDesugaredType();
8033 Qualifiers qs = split.Quals;
8034
8035 // If we have a simple case, just return now.
8036 const auto *ATy = dyn_cast<ArrayType>(split.Ty);
8037 if (!ATy || qs.empty())
8038 return ATy;
8039
8040 // Otherwise, we have an array and we have qualifiers on it. Push the
8041 // qualifiers into the array element type and return a new array type.
8042 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
8043
8044 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
8045 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
8046 CAT->getSizeExpr(),
8047 CAT->getSizeModifier(),
8048 CAT->getIndexTypeCVRQualifiers()));
8049 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
8051 IAT->getSizeModifier(),
8052 IAT->getIndexTypeCVRQualifiers()));
8053
8054 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
8056 NewEltTy, DSAT->getSizeExpr(), DSAT->getSizeModifier(),
8057 DSAT->getIndexTypeCVRQualifiers()));
8058
8059 const auto *VAT = cast<VariableArrayType>(ATy);
8060 return cast<ArrayType>(
8061 getVariableArrayType(NewEltTy, VAT->getSizeExpr(), VAT->getSizeModifier(),
8062 VAT->getIndexTypeCVRQualifiers()));
8063}
8064
8066 if (getLangOpts().HLSL && T.getAddressSpace() == LangAS::hlsl_groupshared)
8067 return getLValueReferenceType(T);
8068 if (getLangOpts().HLSL && T->isConstantArrayType())
8069 return getArrayParameterType(T);
8070 if (T->isArrayType() || T->isFunctionType())
8071 return getDecayedType(T);
8072 return T;
8073}
8074
8078 return T.getUnqualifiedType();
8079}
8080
8082 // C++ [except.throw]p3:
8083 // A throw-expression initializes a temporary object, called the exception
8084 // object, the type of which is determined by removing any top-level
8085 // cv-qualifiers from the static type of the operand of throw and adjusting
8086 // the type from "array of T" or "function returning T" to "pointer to T"
8087 // or "pointer to function returning T", [...]
8089 if (T->isArrayType() || T->isFunctionType())
8090 T = getDecayedType(T);
8091 return T.getUnqualifiedType();
8092}
8093
8094/// getArrayDecayedType - Return the properly qualified result of decaying the
8095/// specified array type to a pointer. This operation is non-trivial when
8096/// handling typedefs etc. The canonical type of "T" must be an array type,
8097/// this returns a pointer to a properly qualified element of the array.
8098///
8099/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
8101 // Get the element type with 'getAsArrayType' so that we don't lose any
8102 // typedefs in the element type of the array. This also handles propagation
8103 // of type qualifiers from the array type into the element type if present
8104 // (C99 6.7.3p8).
8105 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
8106 assert(PrettyArrayType && "Not an array type!");
8107
8108 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
8109
8110 // int x[restrict 4] -> int *restrict
8112 PrettyArrayType->getIndexTypeQualifiers());
8113
8114 // int x[_Nullable] -> int * _Nullable
8115 if (auto Nullability = Ty->getNullability()) {
8116 Result = const_cast<ASTContext *>(this)->getAttributedType(*Nullability,
8117 Result, Result);
8118 }
8119 return Result;
8120}
8121
8123 return getBaseElementType(array->getElementType());
8124}
8125
8127 Qualifiers qs;
8128 while (true) {
8129 SplitQualType split = type.getSplitDesugaredType();
8130 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
8131 if (!array) break;
8132
8133 type = array->getElementType();
8135 }
8136
8137 return getQualifiedType(type, qs);
8138}
8139
8140/// getConstantArrayElementCount - Returns number of constant array elements.
8141uint64_t
8143 uint64_t ElementCount = 1;
8144 do {
8145 ElementCount *= CA->getZExtSize();
8146 CA = dyn_cast_or_null<ConstantArrayType>(
8148 } while (CA);
8149 return ElementCount;
8150}
8151
8153 const ArrayInitLoopExpr *AILE) const {
8154 if (!AILE)
8155 return 0;
8156
8157 uint64_t ElementCount = 1;
8158
8159 do {
8160 ElementCount *= AILE->getArraySize().getZExtValue();
8161 AILE = dyn_cast<ArrayInitLoopExpr>(AILE->getSubExpr());
8162 } while (AILE);
8163
8164 return ElementCount;
8165}
8166
8167/// getFloatingRank - Return a relative rank for floating point types.
8168/// This routine will assert if passed a built-in type that isn't a float.
8170 if (const auto *CT = T->getAs<ComplexType>())
8171 return getFloatingRank(CT->getElementType());
8172
8173 switch (T->castAs<BuiltinType>()->getKind()) {
8174 default: llvm_unreachable("getFloatingRank(): not a floating type");
8175 case BuiltinType::Float16: return Float16Rank;
8176 case BuiltinType::Half: return HalfRank;
8177 case BuiltinType::Float: return FloatRank;
8178 case BuiltinType::Double: return DoubleRank;
8179 case BuiltinType::LongDouble: return LongDoubleRank;
8180 case BuiltinType::Float128: return Float128Rank;
8181 case BuiltinType::BFloat16: return BFloat16Rank;
8182 case BuiltinType::Ibm128: return Ibm128Rank;
8183 }
8184}
8185
8186/// getFloatingTypeOrder - Compare the rank of the two specified floating
8187/// point types, ignoring the domain of the type (i.e. 'double' ==
8188/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
8189/// LHS < RHS, return -1.
8191 FloatingRank LHSR = getFloatingRank(LHS);
8192 FloatingRank RHSR = getFloatingRank(RHS);
8193
8194 if (LHSR == RHSR)
8195 return 0;
8196 if (LHSR > RHSR)
8197 return 1;
8198 return -1;
8199}
8200
8203 return 0;
8204 return getFloatingTypeOrder(LHS, RHS);
8205}
8206
8207/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
8208/// routine will assert if passed a built-in type that isn't an integer or enum,
8209/// or if it is not canonicalized.
8210unsigned ASTContext::getIntegerRank(const Type *T) const {
8211 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
8212
8213 // Results in this 'losing' to any type of the same size, but winning if
8214 // larger.
8215 if (const auto *EIT = dyn_cast<BitIntType>(T))
8216 return 0 + (EIT->getNumBits() << 3);
8217
8218 if (const auto *OBT = dyn_cast<OverflowBehaviorType>(T))
8219 return getIntegerRank(OBT->getUnderlyingType().getTypePtr());
8220
8221 switch (cast<BuiltinType>(T)->getKind()) {
8222 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
8223 case BuiltinType::Bool:
8224 return 1 + (getIntWidth(BoolTy) << 3);
8225 case BuiltinType::Char_S:
8226 case BuiltinType::Char_U:
8227 case BuiltinType::SChar:
8228 case BuiltinType::UChar:
8229 return 2 + (getIntWidth(CharTy) << 3);
8230 case BuiltinType::Short:
8231 case BuiltinType::UShort:
8232 return 3 + (getIntWidth(ShortTy) << 3);
8233 case BuiltinType::Int:
8234 case BuiltinType::UInt:
8235 return 4 + (getIntWidth(IntTy) << 3);
8236 case BuiltinType::Long:
8237 case BuiltinType::ULong:
8238 return 5 + (getIntWidth(LongTy) << 3);
8239 case BuiltinType::LongLong:
8240 case BuiltinType::ULongLong:
8241 return 6 + (getIntWidth(LongLongTy) << 3);
8242 case BuiltinType::Int128:
8243 case BuiltinType::UInt128:
8244 return 7 + (getIntWidth(Int128Ty) << 3);
8245
8246 // "The ranks of char8_t, char16_t, char32_t, and wchar_t equal the ranks of
8247 // their underlying types" [c++20 conv.rank]
8248 case BuiltinType::Char8:
8249 return getIntegerRank(UnsignedCharTy.getTypePtr());
8250 case BuiltinType::Char16:
8251 return getIntegerRank(
8252 getFromTargetType(Target->getChar16Type()).getTypePtr());
8253 case BuiltinType::Char32:
8254 return getIntegerRank(
8255 getFromTargetType(Target->getChar32Type()).getTypePtr());
8256 case BuiltinType::WChar_S:
8257 case BuiltinType::WChar_U:
8258 return getIntegerRank(
8259 getFromTargetType(Target->getWCharType()).getTypePtr());
8260 }
8261}
8262
8263/// Whether this is a promotable bitfield reference according
8264/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
8265///
8266/// \returns the type this bit-field will promote to, or NULL if no
8267/// promotion occurs.
8269 if (E->isTypeDependent() || E->isValueDependent())
8270 return {};
8271
8272 // C++ [conv.prom]p5:
8273 // If the bit-field has an enumerated type, it is treated as any other
8274 // value of that type for promotion purposes.
8276 return {};
8277
8278 // FIXME: We should not do this unless E->refersToBitField() is true. This
8279 // matters in C where getSourceBitField() will find bit-fields for various
8280 // cases where the source expression is not a bit-field designator.
8281
8282 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
8283 if (!Field)
8284 return {};
8285
8286 QualType FT = Field->getType();
8287
8288 uint64_t BitWidth = Field->getBitWidthValue();
8289 uint64_t IntSize = getTypeSize(IntTy);
8290 // C++ [conv.prom]p5:
8291 // A prvalue for an integral bit-field can be converted to a prvalue of type
8292 // int if int can represent all the values of the bit-field; otherwise, it
8293 // can be converted to unsigned int if unsigned int can represent all the
8294 // values of the bit-field. If the bit-field is larger yet, no integral
8295 // promotion applies to it.
8296 // C11 6.3.1.1/2:
8297 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
8298 // If an int can represent all values of the original type (as restricted by
8299 // the width, for a bit-field), the value is converted to an int; otherwise,
8300 // it is converted to an unsigned int.
8301 //
8302 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
8303 // We perform that promotion here to match GCC and C++.
8304 // FIXME: C does not permit promotion of an enum bit-field whose rank is
8305 // greater than that of 'int'. We perform that promotion to match GCC.
8306 //
8307 // C23 6.3.1.1p2:
8308 // The value from a bit-field of a bit-precise integer type is converted to
8309 // the corresponding bit-precise integer type. (The rest is the same as in
8310 // C11.)
8311 if (QualType QT = Field->getType(); QT->isBitIntType())
8312 return QT;
8313
8314 if (BitWidth < IntSize)
8315 return IntTy;
8316
8317 if (BitWidth == IntSize)
8318 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
8319
8320 // Bit-fields wider than int are not subject to promotions, and therefore act
8321 // like the base type. GCC has some weird bugs in this area that we
8322 // deliberately do not follow (GCC follows a pre-standard resolution to
8323 // C's DR315 which treats bit-width as being part of the type, and this leaks
8324 // into their semantics in some cases).
8325 return {};
8326}
8327
8328/// getPromotedIntegerType - Returns the type that Promotable will
8329/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
8330/// integer type.
8332 assert(!Promotable.isNull());
8333 assert(isPromotableIntegerType(Promotable));
8334 if (const auto *ED = Promotable->getAsEnumDecl())
8335 return ED->getPromotionType();
8336
8337 // OverflowBehaviorTypes promote their underlying type and preserve OBT
8338 // qualifier.
8339 if (const auto *OBT = Promotable->getAs<OverflowBehaviorType>()) {
8340 QualType PromotedUnderlying =
8341 getPromotedIntegerType(OBT->getUnderlyingType());
8342 return getOverflowBehaviorType(OBT->getBehaviorKind(), PromotedUnderlying);
8343 }
8344
8345 if (const auto *BT = Promotable->getAs<BuiltinType>()) {
8346 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
8347 // (3.9.1) can be converted to a prvalue of the first of the following
8348 // types that can represent all the values of its underlying type:
8349 // int, unsigned int, long int, unsigned long int, long long int, or
8350 // unsigned long long int [...]
8351 // FIXME: Is there some better way to compute this?
8352 if (BT->getKind() == BuiltinType::WChar_S ||
8353 BT->getKind() == BuiltinType::WChar_U ||
8354 BT->getKind() == BuiltinType::Char8 ||
8355 BT->getKind() == BuiltinType::Char16 ||
8356 BT->getKind() == BuiltinType::Char32) {
8357 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
8358 uint64_t FromSize = getTypeSize(BT);
8359 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
8361 for (const auto &PT : PromoteTypes) {
8362 uint64_t ToSize = getTypeSize(PT);
8363 if (FromSize < ToSize ||
8364 (FromSize == ToSize && FromIsSigned == PT->isSignedIntegerType()))
8365 return PT;
8366 }
8367 llvm_unreachable("char type should fit into long long");
8368 }
8369 }
8370
8371 // At this point, we should have a signed or unsigned integer type.
8372 if (Promotable->isSignedIntegerType())
8373 return IntTy;
8374 uint64_t PromotableSize = getIntWidth(Promotable);
8375 uint64_t IntSize = getIntWidth(IntTy);
8376 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
8377 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
8378}
8379
8380/// Recurses in pointer/array types until it finds an objc retainable
8381/// type and returns its ownership.
8383 while (!T.isNull()) {
8384 if (T.getObjCLifetime() != Qualifiers::OCL_None)
8385 return T.getObjCLifetime();
8386 if (T->isArrayType())
8387 T = getBaseElementType(T);
8388 else if (const auto *PT = T->getAs<PointerType>())
8389 T = PT->getPointeeType();
8390 else if (const auto *RT = T->getAs<ReferenceType>())
8391 T = RT->getPointeeType();
8392 else
8393 break;
8394 }
8395
8396 return Qualifiers::OCL_None;
8397}
8398
8399static const Type *getIntegerTypeForEnum(const EnumType *ET) {
8400 // Incomplete enum types are not treated as integer types.
8401 // FIXME: In C++, enum types are never integer types.
8402 const EnumDecl *ED = ET->getDecl()->getDefinitionOrSelf();
8403 if (ED->isComplete() && !ED->isScoped())
8404 return ED->getIntegerType().getTypePtr();
8405 return nullptr;
8406}
8407
8408/// getIntegerTypeOrder - Returns the highest ranked integer type:
8409/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
8410/// LHS < RHS, return -1.
8412 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
8413 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
8414
8415 // Unwrap enums to their underlying type.
8416 if (const auto *ET = dyn_cast<EnumType>(LHSC))
8417 LHSC = getIntegerTypeForEnum(ET);
8418 if (const auto *ET = dyn_cast<EnumType>(RHSC))
8419 RHSC = getIntegerTypeForEnum(ET);
8420
8421 if (LHSC == RHSC) return 0;
8422
8423 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
8424 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
8425
8426 unsigned LHSRank = getIntegerRank(LHSC);
8427 unsigned RHSRank = getIntegerRank(RHSC);
8428
8429 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
8430 if (LHSRank == RHSRank) return 0;
8431 return LHSRank > RHSRank ? 1 : -1;
8432 }
8433
8434 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
8435 if (LHSUnsigned) {
8436 // If the unsigned [LHS] type is larger, return it.
8437 if (LHSRank >= RHSRank)
8438 return 1;
8439
8440 // If the signed type can represent all values of the unsigned type, it
8441 // wins. Because we are dealing with 2's complement and types that are
8442 // powers of two larger than each other, this is always safe.
8443 return -1;
8444 }
8445
8446 // If the unsigned [RHS] type is larger, return it.
8447 if (RHSRank >= LHSRank)
8448 return -1;
8449
8450 // If the signed type can represent all values of the unsigned type, it
8451 // wins. Because we are dealing with 2's complement and types that are
8452 // powers of two larger than each other, this is always safe.
8453 return 1;
8454}
8455
8457 if (CFConstantStringTypeDecl)
8458 return CFConstantStringTypeDecl;
8459
8460 assert(!CFConstantStringTagDecl &&
8461 "tag and typedef should be initialized together");
8462 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
8463 CFConstantStringTagDecl->startDefinition();
8464
8465 struct {
8466 QualType Type;
8467 const char *Name;
8468 } Fields[5];
8469 unsigned Count = 0;
8470
8471 /// Objective-C ABI
8472 ///
8473 /// typedef struct __NSConstantString_tag {
8474 /// const int *isa;
8475 /// int flags;
8476 /// const char *str;
8477 /// long length;
8478 /// } __NSConstantString;
8479 ///
8480 /// Swift ABI (4.1, 4.2)
8481 ///
8482 /// typedef struct __NSConstantString_tag {
8483 /// uintptr_t _cfisa;
8484 /// uintptr_t _swift_rc;
8485 /// _Atomic(uint64_t) _cfinfoa;
8486 /// const char *_ptr;
8487 /// uint32_t _length;
8488 /// } __NSConstantString;
8489 ///
8490 /// Swift ABI (5.0)
8491 ///
8492 /// typedef struct __NSConstantString_tag {
8493 /// uintptr_t _cfisa;
8494 /// uintptr_t _swift_rc;
8495 /// _Atomic(uint64_t) _cfinfoa;
8496 /// const char *_ptr;
8497 /// uintptr_t _length;
8498 /// } __NSConstantString;
8499
8500 const auto CFRuntime = getLangOpts().CFRuntime;
8501 if (static_cast<unsigned>(CFRuntime) <
8502 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
8503 Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
8504 Fields[Count++] = { IntTy, "flags" };
8505 Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
8506 Fields[Count++] = { LongTy, "length" };
8507 } else {
8508 Fields[Count++] = { getUIntPtrType(), "_cfisa" };
8509 Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
8510 Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
8511 Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
8514 Fields[Count++] = { IntTy, "_ptr" };
8515 else
8516 Fields[Count++] = { getUIntPtrType(), "_ptr" };
8517 }
8518
8519 // Create fields
8520 for (unsigned i = 0; i < Count; ++i) {
8521 FieldDecl *Field =
8522 FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
8523 SourceLocation(), &Idents.get(Fields[i].Name),
8524 Fields[i].Type, /*TInfo=*/nullptr,
8525 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
8526 Field->setAccess(AS_public);
8527 CFConstantStringTagDecl->addDecl(Field);
8528 }
8529
8530 CFConstantStringTagDecl->completeDefinition();
8531 // This type is designed to be compatible with NSConstantString, but cannot
8532 // use the same name, since NSConstantString is an interface.
8533 CanQualType tagType = getCanonicalTagType(CFConstantStringTagDecl);
8534 CFConstantStringTypeDecl =
8535 buildImplicitTypedef(tagType, "__NSConstantString");
8536
8537 return CFConstantStringTypeDecl;
8538}
8539
8541 if (!CFConstantStringTagDecl)
8542 getCFConstantStringDecl(); // Build the tag and the typedef.
8543 return CFConstantStringTagDecl;
8544}
8545
8546// getCFConstantStringType - Return the type used for constant CFStrings.
8551
8553 if (ObjCSuperType.isNull()) {
8554 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
8555 getTranslationUnitDecl()->addDecl(ObjCSuperTypeDecl);
8556 ObjCSuperType = getCanonicalTagType(ObjCSuperTypeDecl);
8557 }
8558 return ObjCSuperType;
8559}
8560
8562 const auto *TT = T->castAs<TypedefType>();
8563 CFConstantStringTypeDecl = cast<TypedefDecl>(TT->getDecl());
8564 CFConstantStringTagDecl = TT->castAsRecordDecl();
8565}
8566
8568 if (BlockDescriptorType)
8569 return getCanonicalTagType(BlockDescriptorType);
8570
8571 RecordDecl *RD;
8572 // FIXME: Needs the FlagAppleBlock bit.
8573 RD = buildImplicitRecord("__block_descriptor");
8574 RD->startDefinition();
8575
8576 QualType FieldTypes[] = {
8579 };
8580
8581 static const char *const FieldNames[] = {
8582 "reserved",
8583 "Size"
8584 };
8585
8586 for (size_t i = 0; i < 2; ++i) {
8588 *this, RD, SourceLocation(), SourceLocation(),
8589 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
8590 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
8591 Field->setAccess(AS_public);
8592 RD->addDecl(Field);
8593 }
8594
8595 RD->completeDefinition();
8596
8597 BlockDescriptorType = RD;
8598
8599 return getCanonicalTagType(BlockDescriptorType);
8600}
8601
8603 if (BlockDescriptorExtendedType)
8604 return getCanonicalTagType(BlockDescriptorExtendedType);
8605
8606 RecordDecl *RD;
8607 // FIXME: Needs the FlagAppleBlock bit.
8608 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
8609 RD->startDefinition();
8610
8611 QualType FieldTypes[] = {
8616 };
8617
8618 static const char *const FieldNames[] = {
8619 "reserved",
8620 "Size",
8621 "CopyFuncPtr",
8622 "DestroyFuncPtr"
8623 };
8624
8625 for (size_t i = 0; i < 4; ++i) {
8627 *this, RD, SourceLocation(), SourceLocation(),
8628 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
8629 /*BitWidth=*/nullptr,
8630 /*Mutable=*/false, ICIS_NoInit);
8631 Field->setAccess(AS_public);
8632 RD->addDecl(Field);
8633 }
8634
8635 RD->completeDefinition();
8636
8637 BlockDescriptorExtendedType = RD;
8638 return getCanonicalTagType(BlockDescriptorExtendedType);
8639}
8640
8642 const auto *BT = dyn_cast<BuiltinType>(T);
8643
8644 if (!BT) {
8645 if (isa<PipeType>(T))
8646 return OCLTK_Pipe;
8647
8648 return OCLTK_Default;
8649 }
8650
8651 switch (BT->getKind()) {
8652#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8653 case BuiltinType::Id: \
8654 return OCLTK_Image;
8655#include "clang/Basic/OpenCLImageTypes.def"
8656
8657 case BuiltinType::OCLClkEvent:
8658 return OCLTK_ClkEvent;
8659
8660 case BuiltinType::OCLEvent:
8661 return OCLTK_Event;
8662
8663 case BuiltinType::OCLQueue:
8664 return OCLTK_Queue;
8665
8666 case BuiltinType::OCLReserveID:
8667 return OCLTK_ReserveID;
8668
8669 case BuiltinType::OCLSampler:
8670 return OCLTK_Sampler;
8671
8672 default:
8673 return OCLTK_Default;
8674 }
8675}
8676
8678 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
8679}
8680
8681/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
8682/// requires copy/dispose. Note that this must match the logic
8683/// in buildByrefHelpers.
8685 const VarDecl *D) {
8686 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
8687 const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
8688 if (!copyExpr && record->hasTrivialDestructor()) return false;
8689
8690 return true;
8691 }
8692
8694 return true;
8695
8696 // The block needs copy/destroy helpers if Ty is non-trivial to destructively
8697 // move or destroy.
8699 return true;
8700
8701 if (!Ty->isObjCRetainableType()) return false;
8702
8703 Qualifiers qs = Ty.getQualifiers();
8704
8705 // If we have lifetime, that dominates.
8706 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
8707 switch (lifetime) {
8708 case Qualifiers::OCL_None: llvm_unreachable("impossible");
8709
8710 // These are just bits as far as the runtime is concerned.
8713 return false;
8714
8715 // These cases should have been taken care of when checking the type's
8716 // non-triviality.
8719 llvm_unreachable("impossible");
8720 }
8721 llvm_unreachable("fell out of lifetime switch!");
8722 }
8723 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
8725}
8726
8728 Qualifiers::ObjCLifetime &LifeTime,
8729 bool &HasByrefExtendedLayout) const {
8730 if (!getLangOpts().ObjC ||
8731 getLangOpts().getGC() != LangOptions::NonGC)
8732 return false;
8733
8734 HasByrefExtendedLayout = false;
8735 if (Ty->isRecordType()) {
8736 HasByrefExtendedLayout = true;
8737 LifeTime = Qualifiers::OCL_None;
8738 } else if ((LifeTime = Ty.getObjCLifetime())) {
8739 // Honor the ARC qualifiers.
8740 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
8741 // The MRR rule.
8743 } else {
8744 LifeTime = Qualifiers::OCL_None;
8745 }
8746 return true;
8747}
8748
8750 assert(Target && "Expected target to be initialized");
8751 const llvm::Triple &T = Target->getTriple();
8752 // Windows is LLP64 rather than LP64
8753 if (T.isOSWindows() && T.isArch64Bit())
8754 return UnsignedLongLongTy;
8755 return UnsignedLongTy;
8756}
8757
8759 assert(Target && "Expected target to be initialized");
8760 const llvm::Triple &T = Target->getTriple();
8761 // Windows is LLP64 rather than LP64
8762 if (T.isOSWindows() && T.isArch64Bit())
8763 return LongLongTy;
8764 return LongTy;
8765}
8766
8768 if (!ObjCInstanceTypeDecl)
8769 ObjCInstanceTypeDecl =
8770 buildImplicitTypedef(getObjCIdType(), "instancetype");
8771 return ObjCInstanceTypeDecl;
8772}
8773
8774// This returns true if a type has been typedefed to BOOL:
8775// typedef <type> BOOL;
8777 if (const auto *TT = dyn_cast<TypedefType>(T))
8778 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
8779 return II->isStr("BOOL");
8780
8781 return false;
8782}
8783
8784/// getObjCEncodingTypeSize returns size of type for objective-c encoding
8785/// purpose.
8787 if (!type->isIncompleteArrayType() && type->isIncompleteType())
8788 return CharUnits::Zero();
8789
8791
8792 // Make all integer and enum types at least as large as an int
8793 if (sz.isPositive() && type->isIntegralOrEnumerationType())
8794 sz = std::max(sz, getTypeSizeInChars(IntTy));
8795 // Treat arrays as pointers, since that's how they're passed in.
8796 else if (type->isArrayType())
8798 return sz;
8799}
8800
8807
8810 if (!VD->isInline())
8812
8813 // In almost all cases, it's a weak definition.
8814 auto *First = VD->getFirstDecl();
8815 if (First->isInlineSpecified() || !First->isStaticDataMember())
8817
8818 // If there's a file-context declaration in this translation unit, it's a
8819 // non-discardable definition.
8820 for (auto *D : VD->redecls())
8822 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
8824
8825 // If we've not seen one yet, we don't know.
8827}
8828
8829static std::string charUnitsToString(const CharUnits &CU) {
8830 return llvm::itostr(CU.getQuantity());
8831}
8832
8833/// getObjCEncodingForBlock - Return the encoded type for this block
8834/// declaration.
8836 std::string S;
8837
8838 const BlockDecl *Decl = Expr->getBlockDecl();
8839 QualType BlockTy =
8841 QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType();
8842 // Encode result type.
8843 if (getLangOpts().EncodeExtendedBlockSig)
8845 true /*Extended*/);
8846 else
8847 getObjCEncodingForType(BlockReturnTy, S);
8848 // Compute size of all parameters.
8849 // Start with computing size of a pointer in number of bytes.
8850 // FIXME: There might(should) be a better way of doing this computation!
8852 CharUnits ParmOffset = PtrSize;
8853 for (auto *PI : Decl->parameters()) {
8854 QualType PType = PI->getType();
8856 if (sz.isZero())
8857 continue;
8858 assert(sz.isPositive() && "BlockExpr - Incomplete param type");
8859 ParmOffset += sz;
8860 }
8861 // Size of the argument frame
8862 S += charUnitsToString(ParmOffset);
8863 // Block pointer and offset.
8864 S += "@?0";
8865
8866 // Argument types.
8867 ParmOffset = PtrSize;
8868 for (auto *PVDecl : Decl->parameters()) {
8869 QualType PType = PVDecl->getOriginalType();
8870 if (const auto *AT =
8871 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8872 // Use array's original type only if it has known number of
8873 // elements.
8874 if (!isa<ConstantArrayType>(AT))
8875 PType = PVDecl->getType();
8876 } else if (PType->isFunctionType())
8877 PType = PVDecl->getType();
8878 if (getLangOpts().EncodeExtendedBlockSig)
8880 S, true /*Extended*/);
8881 else
8882 getObjCEncodingForType(PType, S);
8883 S += charUnitsToString(ParmOffset);
8884 ParmOffset += getObjCEncodingTypeSize(PType);
8885 }
8886
8887 return S;
8888}
8889
8890std::string
8892 std::string S;
8893 // Encode result type.
8894 getObjCEncodingForType(Decl->getReturnType(), S);
8895 CharUnits ParmOffset;
8896 // Compute size of all parameters.
8897 for (auto *PI : Decl->parameters()) {
8898 QualType PType = PI->getType();
8900 if (sz.isZero())
8901 continue;
8902
8903 assert(sz.isPositive() &&
8904 "getObjCEncodingForFunctionDecl - Incomplete param type");
8905 ParmOffset += sz;
8906 }
8907 S += charUnitsToString(ParmOffset);
8908 ParmOffset = CharUnits::Zero();
8909
8910 // Argument types.
8911 for (auto *PVDecl : Decl->parameters()) {
8912 QualType PType = PVDecl->getOriginalType();
8913 if (const auto *AT =
8914 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8915 // Use array's original type only if it has known number of
8916 // elements.
8917 if (!isa<ConstantArrayType>(AT))
8918 PType = PVDecl->getType();
8919 } else if (PType->isFunctionType())
8920 PType = PVDecl->getType();
8921 getObjCEncodingForType(PType, S);
8922 S += charUnitsToString(ParmOffset);
8923 ParmOffset += getObjCEncodingTypeSize(PType);
8924 }
8925
8926 return S;
8927}
8928
8929/// getObjCEncodingForMethodParameter - Return the encoded type for a single
8930/// method parameter or return type. If Extended, include class names and
8931/// block object types.
8933 QualType T, std::string& S,
8934 bool Extended) const {
8935 // Encode type qualifier, 'in', 'inout', etc. for the parameter.
8937 // Encode parameter type.
8938 ObjCEncOptions Options = ObjCEncOptions()
8939 .setExpandPointedToStructures()
8940 .setExpandStructures()
8941 .setIsOutermostType();
8942 if (Extended)
8943 Options.setEncodeBlockParameters().setEncodeClassNames();
8944 getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr);
8945}
8946
8947/// getObjCEncodingForMethodDecl - Return the encoded type for this method
8948/// declaration.
8950 bool Extended) const {
8951 // FIXME: This is not very efficient.
8952 // Encode return type.
8953 std::string S;
8954 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
8955 Decl->getReturnType(), S, Extended);
8956 // Compute size of all parameters.
8957 // Start with computing size of a pointer in number of bytes.
8958 // FIXME: There might(should) be a better way of doing this computation!
8960 // The first two arguments (self and _cmd) are pointers; account for
8961 // their size.
8962 CharUnits ParmOffset = 2 * PtrSize;
8963 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
8964 E = Decl->sel_param_end(); PI != E; ++PI) {
8965 QualType PType = (*PI)->getType();
8967 if (sz.isZero())
8968 continue;
8969
8970 assert(sz.isPositive() &&
8971 "getObjCEncodingForMethodDecl - Incomplete param type");
8972 ParmOffset += sz;
8973 }
8974 S += charUnitsToString(ParmOffset);
8975 S += "@0:";
8976 S += charUnitsToString(PtrSize);
8977
8978 // Argument types.
8979 ParmOffset = 2 * PtrSize;
8980 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
8981 E = Decl->sel_param_end(); PI != E; ++PI) {
8982 const ParmVarDecl *PVDecl = *PI;
8983 QualType PType = PVDecl->getOriginalType();
8984 if (const auto *AT =
8985 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8986 // Use array's original type only if it has known number of
8987 // elements.
8988 if (!isa<ConstantArrayType>(AT))
8989 PType = PVDecl->getType();
8990 } else if (PType->isFunctionType())
8991 PType = PVDecl->getType();
8993 PType, S, Extended);
8994 S += charUnitsToString(ParmOffset);
8995 ParmOffset += getObjCEncodingTypeSize(PType);
8996 }
8997
8998 return S;
8999}
9000
9003 const ObjCPropertyDecl *PD,
9004 const Decl *Container) const {
9005 if (!Container)
9006 return nullptr;
9007 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
9008 for (auto *PID : CID->property_impls())
9009 if (PID->getPropertyDecl() == PD)
9010 return PID;
9011 } else {
9012 const auto *OID = cast<ObjCImplementationDecl>(Container);
9013 for (auto *PID : OID->property_impls())
9014 if (PID->getPropertyDecl() == PD)
9015 return PID;
9016 }
9017 return nullptr;
9018}
9019
9020/// getObjCEncodingForPropertyDecl - Return the encoded type for this
9021/// property declaration. If non-NULL, Container must be either an
9022/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
9023/// NULL when getting encodings for protocol properties.
9024/// Property attributes are stored as a comma-delimited C string. The simple
9025/// attributes readonly and bycopy are encoded as single characters. The
9026/// parametrized attributes, getter=name, setter=name, and ivar=name, are
9027/// encoded as single characters, followed by an identifier. Property types
9028/// are also encoded as a parametrized attribute. The characters used to encode
9029/// these attributes are defined by the following enumeration:
9030/// @code
9031/// enum PropertyAttributes {
9032/// kPropertyReadOnly = 'R', // property is read-only.
9033/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
9034/// kPropertyByref = '&', // property is a reference to the value last assigned
9035/// kPropertyDynamic = 'D', // property is dynamic
9036/// kPropertyGetter = 'G', // followed by getter selector name
9037/// kPropertySetter = 'S', // followed by setter selector name
9038/// kPropertyInstanceVariable = 'V' // followed by instance variable name
9039/// kPropertyType = 'T' // followed by old-style type encoding.
9040/// kPropertyWeak = 'W' // 'weak' property
9041/// kPropertyStrong = 'P' // property GC'able
9042/// kPropertyNonAtomic = 'N' // property non-atomic
9043/// kPropertyOptional = '?' // property optional
9044/// };
9045/// @endcode
9046std::string
9048 const Decl *Container) const {
9049 // Collect information from the property implementation decl(s).
9050 bool Dynamic = false;
9051 ObjCPropertyImplDecl *SynthesizePID = nullptr;
9052
9053 if (ObjCPropertyImplDecl *PropertyImpDecl =
9055 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
9056 Dynamic = true;
9057 else
9058 SynthesizePID = PropertyImpDecl;
9059 }
9060
9061 // FIXME: This is not very efficient.
9062 std::string S = "T";
9063
9064 // Encode result type.
9065 // GCC has some special rules regarding encoding of properties which
9066 // closely resembles encoding of ivars.
9068
9069 if (PD->isOptional())
9070 S += ",?";
9071
9072 if (PD->isReadOnly()) {
9073 S += ",R";
9075 S += ",C";
9077 S += ",&";
9079 S += ",W";
9080 } else {
9081 switch (PD->getSetterKind()) {
9082 case ObjCPropertyDecl::Assign: break;
9083 case ObjCPropertyDecl::Copy: S += ",C"; break;
9084 case ObjCPropertyDecl::Retain: S += ",&"; break;
9085 case ObjCPropertyDecl::Weak: S += ",W"; break;
9086 }
9087 }
9088
9089 // It really isn't clear at all what this means, since properties
9090 // are "dynamic by default".
9091 if (Dynamic)
9092 S += ",D";
9093
9095 S += ",N";
9096
9098 S += ",G";
9099 S += PD->getGetterName().getAsString();
9100 }
9101
9103 S += ",S";
9104 S += PD->getSetterName().getAsString();
9105 }
9106
9107 if (SynthesizePID) {
9108 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
9109 S += ",V";
9110 S += OID->getNameAsString();
9111 }
9112
9113 // FIXME: OBJCGC: weak & strong
9114 return S;
9115}
9116
9117/// getLegacyIntegralTypeEncoding -
9118/// Another legacy compatibility encoding: 32-bit longs are encoded as
9119/// 'l' or 'L' , but not always. For typedefs, we need to use
9120/// 'i' or 'I' instead if encoding a struct field, or a pointer!
9122 if (PointeeTy->getAs<TypedefType>()) {
9123 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
9124 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
9125 PointeeTy = UnsignedIntTy;
9126 else
9127 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
9128 PointeeTy = IntTy;
9129 }
9130 }
9131}
9132
9134 const FieldDecl *Field,
9135 QualType *NotEncodedT) const {
9136 // We follow the behavior of gcc, expanding structures which are
9137 // directly pointed to, and expanding embedded structures. Note that
9138 // these rules are sufficient to prevent recursive encoding of the
9139 // same type.
9140 getObjCEncodingForTypeImpl(T, S,
9141 ObjCEncOptions()
9142 .setExpandPointedToStructures()
9143 .setExpandStructures()
9144 .setIsOutermostType(),
9145 Field, NotEncodedT);
9146}
9147
9149 std::string& S) const {
9150 // Encode result type.
9151 // GCC has some special rules regarding encoding of properties which
9152 // closely resembles encoding of ivars.
9153 getObjCEncodingForTypeImpl(T, S,
9154 ObjCEncOptions()
9155 .setExpandPointedToStructures()
9156 .setExpandStructures()
9157 .setIsOutermostType()
9158 .setEncodingProperty(),
9159 /*Field=*/nullptr);
9160}
9161
9163 const BuiltinType *BT) {
9165 switch (kind) {
9166 case BuiltinType::Void: return 'v';
9167 case BuiltinType::Bool: return 'B';
9168 case BuiltinType::Char8:
9169 case BuiltinType::Char_U:
9170 case BuiltinType::UChar: return 'C';
9171 case BuiltinType::Char16:
9172 case BuiltinType::UShort: return 'S';
9173 case BuiltinType::Char32:
9174 case BuiltinType::UInt: return 'I';
9175 case BuiltinType::ULong:
9176 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
9177 case BuiltinType::UInt128: return 'T';
9178 case BuiltinType::ULongLong: return 'Q';
9179 case BuiltinType::Char_S:
9180 case BuiltinType::SChar: return 'c';
9181 case BuiltinType::Short: return 's';
9182 case BuiltinType::WChar_S:
9183 case BuiltinType::WChar_U:
9184 case BuiltinType::Int: return 'i';
9185 case BuiltinType::Long:
9186 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
9187 case BuiltinType::LongLong: return 'q';
9188 case BuiltinType::Int128: return 't';
9189 case BuiltinType::Float: return 'f';
9190 case BuiltinType::Double: return 'd';
9191 case BuiltinType::LongDouble: return 'D';
9192 case BuiltinType::NullPtr: return '*'; // like char*
9193
9194 case BuiltinType::BFloat16:
9195 case BuiltinType::Float16:
9196 case BuiltinType::Float128:
9197 case BuiltinType::Ibm128:
9198 case BuiltinType::Half:
9199 case BuiltinType::ShortAccum:
9200 case BuiltinType::Accum:
9201 case BuiltinType::LongAccum:
9202 case BuiltinType::UShortAccum:
9203 case BuiltinType::UAccum:
9204 case BuiltinType::ULongAccum:
9205 case BuiltinType::ShortFract:
9206 case BuiltinType::Fract:
9207 case BuiltinType::LongFract:
9208 case BuiltinType::UShortFract:
9209 case BuiltinType::UFract:
9210 case BuiltinType::ULongFract:
9211 case BuiltinType::SatShortAccum:
9212 case BuiltinType::SatAccum:
9213 case BuiltinType::SatLongAccum:
9214 case BuiltinType::SatUShortAccum:
9215 case BuiltinType::SatUAccum:
9216 case BuiltinType::SatULongAccum:
9217 case BuiltinType::SatShortFract:
9218 case BuiltinType::SatFract:
9219 case BuiltinType::SatLongFract:
9220 case BuiltinType::SatUShortFract:
9221 case BuiltinType::SatUFract:
9222 case BuiltinType::SatULongFract:
9223 // FIXME: potentially need @encodes for these!
9224 return ' ';
9225
9226#define SVE_TYPE(Name, Id, SingletonId) \
9227 case BuiltinType::Id:
9228#include "clang/Basic/AArch64ACLETypes.def"
9229#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9230#include "clang/Basic/RISCVVTypes.def"
9231#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9232#include "clang/Basic/WebAssemblyReferenceTypes.def"
9233#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
9234#include "clang/Basic/AMDGPUTypes.def"
9235 {
9236 DiagnosticsEngine &Diags = C->getDiagnostics();
9237 Diags.Report(diag::err_unsupported_objc_primitive_encoding)
9238 << QualType(BT, 0);
9239 return ' ';
9240 }
9241
9242 case BuiltinType::ObjCId:
9243 case BuiltinType::ObjCClass:
9244 case BuiltinType::ObjCSel:
9245 llvm_unreachable("@encoding ObjC primitive type");
9246
9247 // OpenCL and placeholder types don't need @encodings.
9248#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
9249 case BuiltinType::Id:
9250#include "clang/Basic/OpenCLImageTypes.def"
9251#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
9252 case BuiltinType::Id:
9253#include "clang/Basic/OpenCLExtensionTypes.def"
9254 case BuiltinType::OCLEvent:
9255 case BuiltinType::OCLClkEvent:
9256 case BuiltinType::OCLQueue:
9257 case BuiltinType::OCLReserveID:
9258 case BuiltinType::OCLSampler:
9259 case BuiltinType::Dependent:
9260#define PPC_VECTOR_TYPE(Name, Id, Size) \
9261 case BuiltinType::Id:
9262#include "clang/Basic/PPCTypes.def"
9263#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9264#include "clang/Basic/HLSLIntangibleTypes.def"
9265#define BUILTIN_TYPE(KIND, ID)
9266#define PLACEHOLDER_TYPE(KIND, ID) \
9267 case BuiltinType::KIND:
9268#include "clang/AST/BuiltinTypes.def"
9269 llvm_unreachable("invalid builtin type for @encode");
9270 }
9271 llvm_unreachable("invalid BuiltinType::Kind value");
9272}
9273
9274static char ObjCEncodingForEnumDecl(const ASTContext *C, const EnumDecl *ED) {
9276
9277 // The encoding of an non-fixed enum type is always 'i', regardless of size.
9278 if (!Enum->isFixed())
9279 return 'i';
9280
9281 // The encoding of a fixed enum type matches its fixed underlying type.
9282 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
9284}
9285
9286static void EncodeBitField(const ASTContext *Ctx, std::string& S,
9287 QualType T, const FieldDecl *FD) {
9288 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
9289 S += 'b';
9290 // The NeXT runtime encodes bit fields as b followed by the number of bits.
9291 // The GNU runtime requires more information; bitfields are encoded as b,
9292 // then the offset (in bits) of the first element, then the type of the
9293 // bitfield, then the size in bits. For example, in this structure:
9294 //
9295 // struct
9296 // {
9297 // int integer;
9298 // int flags:2;
9299 // };
9300 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
9301 // runtime, but b32i2 for the GNU runtime. The reason for this extra
9302 // information is not especially sensible, but we're stuck with it for
9303 // compatibility with GCC, although providing it breaks anything that
9304 // actually uses runtime introspection and wants to work on both runtimes...
9305 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
9306 uint64_t Offset;
9307
9308 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
9309 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), IVD);
9310 } else {
9311 const RecordDecl *RD = FD->getParent();
9312 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
9313 Offset = RL.getFieldOffset(FD->getFieldIndex());
9314 }
9315
9316 S += llvm::utostr(Offset);
9317
9318 if (const auto *ET = T->getAsCanonical<EnumType>())
9319 S += ObjCEncodingForEnumDecl(Ctx, ET->getDecl());
9320 else {
9321 const auto *BT = T->castAs<BuiltinType>();
9322 S += getObjCEncodingForPrimitiveType(Ctx, BT);
9323 }
9324 }
9325 S += llvm::utostr(FD->getBitWidthValue());
9326}
9327
9328// Helper function for determining whether the encoded type string would include
9329// a template specialization type.
9331 bool VisitBasesAndFields) {
9332 T = T->getBaseElementTypeUnsafe();
9333
9334 if (auto *PT = T->getAs<PointerType>())
9336 PT->getPointeeType().getTypePtr(), false);
9337
9338 auto *CXXRD = T->getAsCXXRecordDecl();
9339
9340 if (!CXXRD)
9341 return false;
9342
9344 return true;
9345
9346 if (!CXXRD->hasDefinition() || !VisitBasesAndFields)
9347 return false;
9348
9349 for (const auto &B : CXXRD->bases())
9350 if (hasTemplateSpecializationInEncodedString(B.getType().getTypePtr(),
9351 true))
9352 return true;
9353
9354 for (auto *FD : CXXRD->fields())
9355 if (hasTemplateSpecializationInEncodedString(FD->getType().getTypePtr(),
9356 true))
9357 return true;
9358
9359 return false;
9360}
9361
9362// FIXME: Use SmallString for accumulating string.
9363void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
9364 const ObjCEncOptions Options,
9365 const FieldDecl *FD,
9366 QualType *NotEncodedT) const {
9368 switch (CT->getTypeClass()) {
9369 case Type::Builtin:
9370 case Type::Enum:
9371 if (FD && FD->isBitField())
9372 return EncodeBitField(this, S, T, FD);
9373 if (const auto *BT = dyn_cast<BuiltinType>(CT))
9374 S += getObjCEncodingForPrimitiveType(this, BT);
9375 else
9376 S += ObjCEncodingForEnumDecl(this, cast<EnumType>(CT)->getDecl());
9377 return;
9378
9379 case Type::Complex:
9380 S += 'j';
9381 getObjCEncodingForTypeImpl(T->castAs<ComplexType>()->getElementType(), S,
9382 ObjCEncOptions(),
9383 /*Field=*/nullptr);
9384 return;
9385
9386 case Type::Atomic:
9387 S += 'A';
9388 getObjCEncodingForTypeImpl(T->castAs<AtomicType>()->getValueType(), S,
9389 ObjCEncOptions(),
9390 /*Field=*/nullptr);
9391 return;
9392
9393 // encoding for pointer or reference types.
9394 case Type::Pointer:
9395 case Type::LValueReference:
9396 case Type::RValueReference: {
9397 QualType PointeeTy;
9398 if (isa<PointerType>(CT)) {
9399 const auto *PT = T->castAs<PointerType>();
9400 if (PT->isObjCSelType()) {
9401 S += ':';
9402 return;
9403 }
9404 PointeeTy = PT->getPointeeType();
9405 } else {
9406 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
9407 }
9408
9409 bool isReadOnly = false;
9410 // For historical/compatibility reasons, the read-only qualifier of the
9411 // pointee gets emitted _before_ the '^'. The read-only qualifier of
9412 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
9413 // Also, do not emit the 'r' for anything but the outermost type!
9414 if (T->getAs<TypedefType>()) {
9415 if (Options.IsOutermostType() && T.isConstQualified()) {
9416 isReadOnly = true;
9417 S += 'r';
9418 }
9419 } else if (Options.IsOutermostType()) {
9420 QualType P = PointeeTy;
9421 while (auto PT = P->getAs<PointerType>())
9422 P = PT->getPointeeType();
9423 if (P.isConstQualified()) {
9424 isReadOnly = true;
9425 S += 'r';
9426 }
9427 }
9428 if (isReadOnly) {
9429 // Another legacy compatibility encoding. Some ObjC qualifier and type
9430 // combinations need to be rearranged.
9431 // Rewrite "in const" from "nr" to "rn"
9432 if (StringRef(S).ends_with("nr"))
9433 S.replace(S.end()-2, S.end(), "rn");
9434 }
9435
9436 if (PointeeTy->isCharType()) {
9437 // char pointer types should be encoded as '*' unless it is a
9438 // type that has been typedef'd to 'BOOL'.
9439 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
9440 S += '*';
9441 return;
9442 }
9443 } else if (const auto *RTy = PointeeTy->getAsCanonical<RecordType>()) {
9444 const IdentifierInfo *II = RTy->getDecl()->getIdentifier();
9445 // GCC binary compat: Need to convert "struct objc_class *" to "#".
9446 if (II == &Idents.get("objc_class")) {
9447 S += '#';
9448 return;
9449 }
9450 // GCC binary compat: Need to convert "struct objc_object *" to "@".
9451 if (II == &Idents.get("objc_object")) {
9452 S += '@';
9453 return;
9454 }
9455 // If the encoded string for the class includes template names, just emit
9456 // "^v" for pointers to the class.
9457 if (getLangOpts().CPlusPlus &&
9458 (!getLangOpts().EncodeCXXClassTemplateSpec &&
9460 RTy, Options.ExpandPointedToStructures()))) {
9461 S += "^v";
9462 return;
9463 }
9464 // fall through...
9465 }
9466 S += '^';
9468
9469 ObjCEncOptions NewOptions;
9470 if (Options.ExpandPointedToStructures())
9471 NewOptions.setExpandStructures();
9472 getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions,
9473 /*Field=*/nullptr, NotEncodedT);
9474 return;
9475 }
9476
9477 case Type::ConstantArray:
9478 case Type::IncompleteArray:
9479 case Type::VariableArray: {
9480 const auto *AT = cast<ArrayType>(CT);
9481
9482 if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) {
9483 // Incomplete arrays are encoded as a pointer to the array element.
9484 S += '^';
9485
9486 getObjCEncodingForTypeImpl(
9487 AT->getElementType(), S,
9488 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD);
9489 } else {
9490 S += '[';
9491
9492 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
9493 S += llvm::utostr(CAT->getZExtSize());
9494 else {
9495 //Variable length arrays are encoded as a regular array with 0 elements.
9497 "Unknown array type!");
9498 S += '0';
9499 }
9500
9501 getObjCEncodingForTypeImpl(
9502 AT->getElementType(), S,
9503 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD,
9504 NotEncodedT);
9505 S += ']';
9506 }
9507 return;
9508 }
9509
9510 case Type::FunctionNoProto:
9511 case Type::FunctionProto:
9512 S += '?';
9513 return;
9514
9515 case Type::Record: {
9516 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
9517 S += RDecl->isUnion() ? '(' : '{';
9518 // Anonymous structures print as '?'
9519 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
9520 S += II->getName();
9521 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
9522 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
9523 llvm::raw_string_ostream OS(S);
9524 printTemplateArgumentList(OS, TemplateArgs.asArray(),
9526 }
9527 } else {
9528 S += '?';
9529 }
9530 if (Options.ExpandStructures()) {
9531 S += '=';
9532 if (!RDecl->isUnion()) {
9533 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
9534 } else {
9535 for (const auto *Field : RDecl->fields()) {
9536 if (FD) {
9537 S += '"';
9538 S += Field->getNameAsString();
9539 S += '"';
9540 }
9541
9542 // Special case bit-fields.
9543 if (Field->isBitField()) {
9544 getObjCEncodingForTypeImpl(Field->getType(), S,
9545 ObjCEncOptions().setExpandStructures(),
9546 Field);
9547 } else {
9548 QualType qt = Field->getType();
9550 getObjCEncodingForTypeImpl(
9551 qt, S,
9552 ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
9553 NotEncodedT);
9554 }
9555 }
9556 }
9557 }
9558 S += RDecl->isUnion() ? ')' : '}';
9559 return;
9560 }
9561
9562 case Type::BlockPointer: {
9563 const auto *BT = T->castAs<BlockPointerType>();
9564 S += "@?"; // Unlike a pointer-to-function, which is "^?".
9565 if (Options.EncodeBlockParameters()) {
9566 const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
9567
9568 S += '<';
9569 // Block return type
9570 getObjCEncodingForTypeImpl(FT->getReturnType(), S,
9571 Options.forComponentType(), FD, NotEncodedT);
9572 // Block self
9573 S += "@?";
9574 // Block parameters
9575 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
9576 for (const auto &I : FPT->param_types())
9577 getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD,
9578 NotEncodedT);
9579 }
9580 S += '>';
9581 }
9582 return;
9583 }
9584
9585 case Type::ObjCObject: {
9586 // hack to match legacy encoding of *id and *Class
9587 QualType Ty = getObjCObjectPointerType(CT);
9588 if (Ty->isObjCIdType()) {
9589 S += "{objc_object=}";
9590 return;
9591 }
9592 else if (Ty->isObjCClassType()) {
9593 S += "{objc_class=}";
9594 return;
9595 }
9596 // TODO: Double check to make sure this intentionally falls through.
9597 [[fallthrough]];
9598 }
9599
9600 case Type::ObjCInterface: {
9601 // Ignore protocol qualifiers when mangling at this level.
9602 // @encode(class_name)
9603 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
9604 S += '{';
9605 S += OI->getObjCRuntimeNameAsString();
9606 if (Options.ExpandStructures()) {
9607 S += '=';
9608 SmallVector<const ObjCIvarDecl*, 32> Ivars;
9609 DeepCollectObjCIvars(OI, true, Ivars);
9610 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
9611 const FieldDecl *Field = Ivars[i];
9612 if (Field->isBitField())
9613 getObjCEncodingForTypeImpl(Field->getType(), S,
9614 ObjCEncOptions().setExpandStructures(),
9615 Field);
9616 else
9617 getObjCEncodingForTypeImpl(Field->getType(), S,
9618 ObjCEncOptions().setExpandStructures(), FD,
9619 NotEncodedT);
9620 }
9621 }
9622 S += '}';
9623 return;
9624 }
9625
9626 case Type::ObjCObjectPointer: {
9627 const auto *OPT = T->castAs<ObjCObjectPointerType>();
9628 if (OPT->isObjCIdType()) {
9629 S += '@';
9630 return;
9631 }
9632
9633 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
9634 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
9635 // Since this is a binary compatibility issue, need to consult with
9636 // runtime folks. Fortunately, this is a *very* obscure construct.
9637 S += '#';
9638 return;
9639 }
9640
9641 if (OPT->isObjCQualifiedIdType()) {
9642 getObjCEncodingForTypeImpl(
9643 getObjCIdType(), S,
9644 Options.keepingOnly(ObjCEncOptions()
9645 .setExpandPointedToStructures()
9646 .setExpandStructures()),
9647 FD);
9648 if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
9649 // Note that we do extended encoding of protocol qualifier list
9650 // Only when doing ivar or property encoding.
9651 S += '"';
9652 for (const auto *I : OPT->quals()) {
9653 S += '<';
9654 S += I->getObjCRuntimeNameAsString();
9655 S += '>';
9656 }
9657 S += '"';
9658 }
9659 return;
9660 }
9661
9662 S += '@';
9663 if (OPT->getInterfaceDecl() &&
9664 (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
9665 S += '"';
9666 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
9667 for (const auto *I : OPT->quals()) {
9668 S += '<';
9669 S += I->getObjCRuntimeNameAsString();
9670 S += '>';
9671 }
9672 S += '"';
9673 }
9674 return;
9675 }
9676
9677 // gcc just blithely ignores member pointers.
9678 // FIXME: we should do better than that. 'M' is available.
9679 case Type::MemberPointer:
9680 // This matches gcc's encoding, even though technically it is insufficient.
9681 //FIXME. We should do a better job than gcc.
9682 case Type::Vector:
9683 case Type::ExtVector:
9684 // Until we have a coherent encoding of these three types, issue warning.
9685 if (NotEncodedT)
9686 *NotEncodedT = T;
9687 return;
9688
9689 case Type::ConstantMatrix:
9690 if (NotEncodedT)
9691 *NotEncodedT = T;
9692 return;
9693
9694 case Type::BitInt:
9695 if (NotEncodedT)
9696 *NotEncodedT = T;
9697 return;
9698
9699 // We could see an undeduced auto type here during error recovery.
9700 // Just ignore it.
9701 case Type::Auto:
9702 case Type::DeducedTemplateSpecialization:
9703 return;
9704
9705 case Type::HLSLAttributedResource:
9706 case Type::HLSLInlineSpirv:
9707 case Type::OverflowBehavior:
9708 llvm_unreachable("unexpected type");
9709
9710 case Type::ArrayParameter:
9711 case Type::Pipe:
9712#define ABSTRACT_TYPE(KIND, BASE)
9713#define TYPE(KIND, BASE)
9714#define DEPENDENT_TYPE(KIND, BASE) \
9715 case Type::KIND:
9716#define NON_CANONICAL_TYPE(KIND, BASE) \
9717 case Type::KIND:
9718#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
9719 case Type::KIND:
9720#include "clang/AST/TypeNodes.inc"
9721 llvm_unreachable("@encode for dependent type!");
9722 }
9723 llvm_unreachable("bad type kind!");
9724}
9725
9726void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
9727 std::string &S,
9728 const FieldDecl *FD,
9729 bool includeVBases,
9730 QualType *NotEncodedT) const {
9731 assert(RDecl && "Expected non-null RecordDecl");
9732 assert(!RDecl->isUnion() && "Should not be called for unions");
9733 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
9734 return;
9735
9736 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
9737 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
9738 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
9739
9740 if (CXXRec) {
9741 for (const auto &BI : CXXRec->bases()) {
9742 if (!BI.isVirtual()) {
9743 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9744 if (base->isEmpty())
9745 continue;
9746 uint64_t offs = toBits(layout.getBaseClassOffset(base));
9747 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9748 std::make_pair(offs, base));
9749 }
9750 }
9751 }
9752
9753 for (FieldDecl *Field : RDecl->fields()) {
9754 if (!Field->isZeroLengthBitField() && Field->isZeroSize(*this))
9755 continue;
9756 uint64_t offs = layout.getFieldOffset(Field->getFieldIndex());
9757 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9758 std::make_pair(offs, Field));
9759 }
9760
9761 if (CXXRec && includeVBases) {
9762 for (const auto &BI : CXXRec->vbases()) {
9763 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9764 if (base->isEmpty())
9765 continue;
9766 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
9767 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
9768 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
9769 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
9770 std::make_pair(offs, base));
9771 }
9772 }
9773
9774 CharUnits size;
9775 if (CXXRec) {
9776 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
9777 } else {
9778 size = layout.getSize();
9779 }
9780
9781#ifndef NDEBUG
9782 uint64_t CurOffs = 0;
9783#endif
9784 std::multimap<uint64_t, NamedDecl *>::iterator
9785 CurLayObj = FieldOrBaseOffsets.begin();
9786
9787 if (CXXRec && CXXRec->isDynamicClass() &&
9788 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
9789 if (FD) {
9790 S += "\"_vptr$";
9791 std::string recname = CXXRec->getNameAsString();
9792 if (recname.empty()) recname = "?";
9793 S += recname;
9794 S += '"';
9795 }
9796 S += "^^?";
9797#ifndef NDEBUG
9798 CurOffs += getTypeSize(VoidPtrTy);
9799#endif
9800 }
9801
9802 if (!RDecl->hasFlexibleArrayMember()) {
9803 // Mark the end of the structure.
9804 uint64_t offs = toBits(size);
9805 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9806 std::make_pair(offs, nullptr));
9807 }
9808
9809 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
9810#ifndef NDEBUG
9811 assert(CurOffs <= CurLayObj->first);
9812 if (CurOffs < CurLayObj->first) {
9813 uint64_t padding = CurLayObj->first - CurOffs;
9814 // FIXME: There doesn't seem to be a way to indicate in the encoding that
9815 // packing/alignment of members is different that normal, in which case
9816 // the encoding will be out-of-sync with the real layout.
9817 // If the runtime switches to just consider the size of types without
9818 // taking into account alignment, we could make padding explicit in the
9819 // encoding (e.g. using arrays of chars). The encoding strings would be
9820 // longer then though.
9821 CurOffs += padding;
9822 }
9823#endif
9824
9825 NamedDecl *dcl = CurLayObj->second;
9826 if (!dcl)
9827 break; // reached end of structure.
9828
9829 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
9830 // We expand the bases without their virtual bases since those are going
9831 // in the initial structure. Note that this differs from gcc which
9832 // expands virtual bases each time one is encountered in the hierarchy,
9833 // making the encoding type bigger than it really is.
9834 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
9835 NotEncodedT);
9836 assert(!base->isEmpty());
9837#ifndef NDEBUG
9838 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
9839#endif
9840 } else {
9841 const auto *field = cast<FieldDecl>(dcl);
9842 if (FD) {
9843 S += '"';
9844 S += field->getNameAsString();
9845 S += '"';
9846 }
9847
9848 if (field->isBitField()) {
9849 EncodeBitField(this, S, field->getType(), field);
9850#ifndef NDEBUG
9851 CurOffs += field->getBitWidthValue();
9852#endif
9853 } else {
9854 QualType qt = field->getType();
9856 getObjCEncodingForTypeImpl(
9857 qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(),
9858 FD, NotEncodedT);
9859#ifndef NDEBUG
9860 CurOffs += getTypeSize(field->getType());
9861#endif
9862 }
9863 }
9864 }
9865}
9866
9868 std::string& S) const {
9869 if (QT & Decl::OBJC_TQ_In)
9870 S += 'n';
9871 if (QT & Decl::OBJC_TQ_Inout)
9872 S += 'N';
9873 if (QT & Decl::OBJC_TQ_Out)
9874 S += 'o';
9875 if (QT & Decl::OBJC_TQ_Bycopy)
9876 S += 'O';
9877 if (QT & Decl::OBJC_TQ_Byref)
9878 S += 'R';
9879 if (QT & Decl::OBJC_TQ_Oneway)
9880 S += 'V';
9881}
9882
9884 if (!ObjCIdDecl) {
9887 ObjCIdDecl = buildImplicitTypedef(T, "id");
9888 }
9889 return ObjCIdDecl;
9890}
9891
9893 if (!ObjCSelDecl) {
9895 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
9896 }
9897 return ObjCSelDecl;
9898}
9899
9901 if (!ObjCClassDecl) {
9904 ObjCClassDecl = buildImplicitTypedef(T, "Class");
9905 }
9906 return ObjCClassDecl;
9907}
9908
9910 if (!ObjCProtocolClassDecl) {
9911 ObjCProtocolClassDecl
9914 &Idents.get("Protocol"),
9915 /*typeParamList=*/nullptr,
9916 /*PrevDecl=*/nullptr,
9917 SourceLocation(), true);
9918 }
9919
9920 return ObjCProtocolClassDecl;
9921}
9922
9924 if (!getLangOpts().PointerAuthObjcInterfaceSel)
9925 return PointerAuthQualifier();
9927 getLangOpts().PointerAuthObjcInterfaceSelKey,
9928 /*isAddressDiscriminated=*/true, SelPointerConstantDiscriminator,
9930 /*isIsaPointer=*/false,
9931 /*authenticatesNullValues=*/false);
9932}
9933
9934//===----------------------------------------------------------------------===//
9935// __builtin_va_list Construction Functions
9936//===----------------------------------------------------------------------===//
9937
9939 StringRef Name) {
9940 // typedef char* __builtin[_ms]_va_list;
9941 QualType T = Context->getPointerType(Context->CharTy);
9942 return Context->buildImplicitTypedef(T, Name);
9943}
9944
9946 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
9947}
9948
9950 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
9951}
9952
9954 // typedef void* __builtin_va_list;
9955 QualType T = Context->getPointerType(Context->VoidTy);
9956 return Context->buildImplicitTypedef(T, "__builtin_va_list");
9957}
9958
9959static TypedefDecl *
9961 // struct __va_list
9962 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
9963 if (Context->getLangOpts().CPlusPlus) {
9964 // namespace std { struct __va_list {
9965 auto *NS = NamespaceDecl::Create(
9966 const_cast<ASTContext &>(*Context), Context->getTranslationUnitDecl(),
9967 /*Inline=*/false, SourceLocation(), SourceLocation(),
9968 &Context->Idents.get("std"),
9969 /*PrevDecl=*/nullptr, /*Nested=*/false);
9970 NS->setImplicit();
9972 }
9973
9974 VaListTagDecl->startDefinition();
9975
9976 const size_t NumFields = 5;
9977 QualType FieldTypes[NumFields];
9978 const char *FieldNames[NumFields];
9979
9980 // void *__stack;
9981 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
9982 FieldNames[0] = "__stack";
9983
9984 // void *__gr_top;
9985 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
9986 FieldNames[1] = "__gr_top";
9987
9988 // void *__vr_top;
9989 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
9990 FieldNames[2] = "__vr_top";
9991
9992 // int __gr_offs;
9993 FieldTypes[3] = Context->IntTy;
9994 FieldNames[3] = "__gr_offs";
9995
9996 // int __vr_offs;
9997 FieldTypes[4] = Context->IntTy;
9998 FieldNames[4] = "__vr_offs";
9999
10000 // Create fields
10001 for (unsigned i = 0; i < NumFields; ++i) {
10002 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10006 &Context->Idents.get(FieldNames[i]),
10007 FieldTypes[i], /*TInfo=*/nullptr,
10008 /*BitWidth=*/nullptr,
10009 /*Mutable=*/false,
10010 ICIS_NoInit);
10011 Field->setAccess(AS_public);
10012 VaListTagDecl->addDecl(Field);
10013 }
10014 VaListTagDecl->completeDefinition();
10015 Context->VaListTagDecl = VaListTagDecl;
10016 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10017
10018 // } __builtin_va_list;
10019 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
10020}
10021
10023 // typedef struct __va_list_tag {
10025
10026 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10027 VaListTagDecl->startDefinition();
10028
10029 const size_t NumFields = 5;
10030 QualType FieldTypes[NumFields];
10031 const char *FieldNames[NumFields];
10032
10033 // unsigned char gpr;
10034 FieldTypes[0] = Context->UnsignedCharTy;
10035 FieldNames[0] = "gpr";
10036
10037 // unsigned char fpr;
10038 FieldTypes[1] = Context->UnsignedCharTy;
10039 FieldNames[1] = "fpr";
10040
10041 // unsigned short reserved;
10042 FieldTypes[2] = Context->UnsignedShortTy;
10043 FieldNames[2] = "reserved";
10044
10045 // void* overflow_arg_area;
10046 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
10047 FieldNames[3] = "overflow_arg_area";
10048
10049 // void* reg_save_area;
10050 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
10051 FieldNames[4] = "reg_save_area";
10052
10053 // Create fields
10054 for (unsigned i = 0; i < NumFields; ++i) {
10055 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
10058 &Context->Idents.get(FieldNames[i]),
10059 FieldTypes[i], /*TInfo=*/nullptr,
10060 /*BitWidth=*/nullptr,
10061 /*Mutable=*/false,
10062 ICIS_NoInit);
10063 Field->setAccess(AS_public);
10064 VaListTagDecl->addDecl(Field);
10065 }
10066 VaListTagDecl->completeDefinition();
10067 Context->VaListTagDecl = VaListTagDecl;
10068 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10069
10070 // } __va_list_tag;
10071 TypedefDecl *VaListTagTypedefDecl =
10072 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
10073
10074 QualType VaListTagTypedefType =
10075 Context->getTypedefType(ElaboratedTypeKeyword::None,
10076 /*Qualifier=*/std::nullopt, VaListTagTypedefDecl);
10077
10078 // typedef __va_list_tag __builtin_va_list[1];
10079 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10080 QualType VaListTagArrayType = Context->getConstantArrayType(
10081 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
10082 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10083}
10084
10085static TypedefDecl *
10087 // struct __va_list_tag {
10089 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10090 VaListTagDecl->startDefinition();
10091
10092 const size_t NumFields = 4;
10093 QualType FieldTypes[NumFields];
10094 const char *FieldNames[NumFields];
10095
10096 // unsigned gp_offset;
10097 FieldTypes[0] = Context->UnsignedIntTy;
10098 FieldNames[0] = "gp_offset";
10099
10100 // unsigned fp_offset;
10101 FieldTypes[1] = Context->UnsignedIntTy;
10102 FieldNames[1] = "fp_offset";
10103
10104 // void* overflow_arg_area;
10105 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10106 FieldNames[2] = "overflow_arg_area";
10107
10108 // void* reg_save_area;
10109 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
10110 FieldNames[3] = "reg_save_area";
10111
10112 // Create fields
10113 for (unsigned i = 0; i < NumFields; ++i) {
10114 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10118 &Context->Idents.get(FieldNames[i]),
10119 FieldTypes[i], /*TInfo=*/nullptr,
10120 /*BitWidth=*/nullptr,
10121 /*Mutable=*/false,
10122 ICIS_NoInit);
10123 Field->setAccess(AS_public);
10124 VaListTagDecl->addDecl(Field);
10125 }
10126 VaListTagDecl->completeDefinition();
10127 Context->VaListTagDecl = VaListTagDecl;
10128 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10129
10130 // };
10131
10132 // typedef struct __va_list_tag __builtin_va_list[1];
10133 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10134 QualType VaListTagArrayType = Context->getConstantArrayType(
10135 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
10136 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10137}
10138
10139static TypedefDecl *
10141 // struct __va_list
10142 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
10143 if (Context->getLangOpts().CPlusPlus) {
10144 // namespace std { struct __va_list {
10145 NamespaceDecl *NS;
10146 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
10147 Context->getTranslationUnitDecl(),
10148 /*Inline=*/false, SourceLocation(),
10149 SourceLocation(), &Context->Idents.get("std"),
10150 /*PrevDecl=*/nullptr, /*Nested=*/false);
10151 NS->setImplicit();
10152 VaListDecl->setDeclContext(NS);
10153 }
10154
10155 VaListDecl->startDefinition();
10156
10157 // void * __ap;
10158 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10159 VaListDecl,
10162 &Context->Idents.get("__ap"),
10163 Context->getPointerType(Context->VoidTy),
10164 /*TInfo=*/nullptr,
10165 /*BitWidth=*/nullptr,
10166 /*Mutable=*/false,
10167 ICIS_NoInit);
10168 Field->setAccess(AS_public);
10169 VaListDecl->addDecl(Field);
10170
10171 // };
10172 VaListDecl->completeDefinition();
10173 Context->VaListTagDecl = VaListDecl;
10174
10175 // typedef struct __va_list __builtin_va_list;
10176 CanQualType T = Context->getCanonicalTagType(VaListDecl);
10177 return Context->buildImplicitTypedef(T, "__builtin_va_list");
10178}
10179
10180static TypedefDecl *
10182 // struct __va_list_tag {
10184 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10185 VaListTagDecl->startDefinition();
10186
10187 const size_t NumFields = 4;
10188 QualType FieldTypes[NumFields];
10189 const char *FieldNames[NumFields];
10190
10191 // long __gpr;
10192 FieldTypes[0] = Context->LongTy;
10193 FieldNames[0] = "__gpr";
10194
10195 // long __fpr;
10196 FieldTypes[1] = Context->LongTy;
10197 FieldNames[1] = "__fpr";
10198
10199 // void *__overflow_arg_area;
10200 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10201 FieldNames[2] = "__overflow_arg_area";
10202
10203 // void *__reg_save_area;
10204 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
10205 FieldNames[3] = "__reg_save_area";
10206
10207 // Create fields
10208 for (unsigned i = 0; i < NumFields; ++i) {
10209 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10213 &Context->Idents.get(FieldNames[i]),
10214 FieldTypes[i], /*TInfo=*/nullptr,
10215 /*BitWidth=*/nullptr,
10216 /*Mutable=*/false,
10217 ICIS_NoInit);
10218 Field->setAccess(AS_public);
10219 VaListTagDecl->addDecl(Field);
10220 }
10221 VaListTagDecl->completeDefinition();
10222 Context->VaListTagDecl = VaListTagDecl;
10223 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10224
10225 // };
10226
10227 // typedef __va_list_tag __builtin_va_list[1];
10228 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10229 QualType VaListTagArrayType = Context->getConstantArrayType(
10230 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
10231
10232 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10233}
10234
10236 // typedef struct __va_list_tag {
10238 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10239 VaListTagDecl->startDefinition();
10240
10241 const size_t NumFields = 3;
10242 QualType FieldTypes[NumFields];
10243 const char *FieldNames[NumFields];
10244
10245 // void *CurrentSavedRegisterArea;
10246 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
10247 FieldNames[0] = "__current_saved_reg_area_pointer";
10248
10249 // void *SavedRegAreaEnd;
10250 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
10251 FieldNames[1] = "__saved_reg_area_end_pointer";
10252
10253 // void *OverflowArea;
10254 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10255 FieldNames[2] = "__overflow_area_pointer";
10256
10257 // Create fields
10258 for (unsigned i = 0; i < NumFields; ++i) {
10260 const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(),
10261 SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i],
10262 /*TInfo=*/nullptr,
10263 /*BitWidth=*/nullptr,
10264 /*Mutable=*/false, ICIS_NoInit);
10265 Field->setAccess(AS_public);
10266 VaListTagDecl->addDecl(Field);
10267 }
10268 VaListTagDecl->completeDefinition();
10269 Context->VaListTagDecl = VaListTagDecl;
10270 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10271
10272 // } __va_list_tag;
10273 TypedefDecl *VaListTagTypedefDecl =
10274 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
10275
10276 QualType VaListTagTypedefType =
10277 Context->getTypedefType(ElaboratedTypeKeyword::None,
10278 /*Qualifier=*/std::nullopt, VaListTagTypedefDecl);
10279
10280 // typedef __va_list_tag __builtin_va_list[1];
10281 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10282 QualType VaListTagArrayType = Context->getConstantArrayType(
10283 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
10284
10285 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10286}
10287
10288static TypedefDecl *
10290 // typedef struct __va_list_tag {
10291 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10292
10293 VaListTagDecl->startDefinition();
10294
10295 // int* __va_stk;
10296 // int* __va_reg;
10297 // int __va_ndx;
10298 constexpr size_t NumFields = 3;
10299 QualType FieldTypes[NumFields] = {Context->getPointerType(Context->IntTy),
10300 Context->getPointerType(Context->IntTy),
10301 Context->IntTy};
10302 const char *FieldNames[NumFields] = {"__va_stk", "__va_reg", "__va_ndx"};
10303
10304 // Create fields
10305 for (unsigned i = 0; i < NumFields; ++i) {
10308 &Context->Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
10309 /*BitWidth=*/nullptr,
10310 /*Mutable=*/false, ICIS_NoInit);
10311 Field->setAccess(AS_public);
10312 VaListTagDecl->addDecl(Field);
10313 }
10314 VaListTagDecl->completeDefinition();
10315 Context->VaListTagDecl = VaListTagDecl;
10316 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10317
10318 // } __va_list_tag;
10319 TypedefDecl *VaListTagTypedefDecl =
10320 Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
10321
10322 return VaListTagTypedefDecl;
10323}
10324
10327 switch (Kind) {
10329 return CreateCharPtrBuiltinVaListDecl(Context);
10331 return CreateVoidPtrBuiltinVaListDecl(Context);
10333 return CreateAArch64ABIBuiltinVaListDecl(Context);
10335 return CreatePowerABIBuiltinVaListDecl(Context);
10337 return CreateX86_64ABIBuiltinVaListDecl(Context);
10339 return CreateAAPCSABIBuiltinVaListDecl(Context);
10341 return CreateSystemZBuiltinVaListDecl(Context);
10343 return CreateHexagonBuiltinVaListDecl(Context);
10345 return CreateXtensaABIBuiltinVaListDecl(Context);
10346 }
10347
10348 llvm_unreachable("Unhandled __builtin_va_list type kind");
10349}
10350
10352 if (!BuiltinVaListDecl) {
10353 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
10354 assert(BuiltinVaListDecl->isImplicit());
10355 }
10356
10357 return BuiltinVaListDecl;
10358}
10359
10361 // Force the creation of VaListTagDecl by building the __builtin_va_list
10362 // declaration.
10363 if (!VaListTagDecl)
10364 (void)getBuiltinVaListDecl();
10365
10366 return VaListTagDecl;
10367}
10368
10370 if (!BuiltinMSVaListDecl)
10371 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
10372
10373 return BuiltinMSVaListDecl;
10374}
10375
10377 // Allow redecl custom type checking builtin for HLSL.
10378 if (LangOpts.HLSL && FD->getBuiltinID() != Builtin::NotBuiltin &&
10379 BuiltinInfo.hasCustomTypechecking(FD->getBuiltinID()))
10380 return true;
10381 // Allow redecl custom type checking builtin for SPIR-V.
10382 if (getTargetInfo().getTriple().isSPIROrSPIRV() &&
10383 BuiltinInfo.isTSBuiltin(FD->getBuiltinID()) &&
10384 BuiltinInfo.hasCustomTypechecking(FD->getBuiltinID()))
10385 return true;
10386 return BuiltinInfo.canBeRedeclared(FD->getBuiltinID());
10387}
10388
10390 assert(ObjCConstantStringType.isNull() &&
10391 "'NSConstantString' type already set!");
10392
10393 ObjCConstantStringType = getObjCInterfaceType(Decl);
10394}
10395
10396/// Retrieve the template name that corresponds to a non-empty
10397/// lookup.
10400 UnresolvedSetIterator End) const {
10401 unsigned size = End - Begin;
10402 assert(size > 1 && "set is not overloaded!");
10403
10404 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
10405 size * sizeof(FunctionTemplateDecl*));
10406 auto *OT = new (memory) OverloadedTemplateStorage(size);
10407
10408 NamedDecl **Storage = OT->getStorage();
10409 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
10410 NamedDecl *D = *I;
10411 assert(isa<FunctionTemplateDecl>(D) ||
10415 *Storage++ = D;
10416 }
10417
10418 return TemplateName(OT);
10419}
10420
10421/// Retrieve a template name representing an unqualified-id that has been
10422/// assumed to name a template for ADL purposes.
10424 auto *OT = new (*this) AssumedTemplateStorage(Name);
10425 return TemplateName(OT);
10426}
10427
10428/// Retrieve the template name that represents a qualified
10429/// template name such as \c std::vector.
10431 bool TemplateKeyword,
10432 TemplateName Template) const {
10433 assert(Template.getKind() == TemplateName::Template ||
10435
10436 if (Template.getAsTemplateDecl()->getKind() == Decl::TemplateTemplateParm) {
10437 assert(!Qualifier && "unexpected qualified template template parameter");
10438 assert(TemplateKeyword == false);
10439 return Template;
10440 }
10441
10442 // FIXME: Canonicalization?
10443 llvm::FoldingSetNodeID ID;
10444 QualifiedTemplateName::Profile(ID, Qualifier, TemplateKeyword, Template);
10445
10446 void *InsertPos = nullptr;
10448 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
10449 if (!QTN) {
10450 QTN = new (*this, alignof(QualifiedTemplateName))
10451 QualifiedTemplateName(Qualifier, TemplateKeyword, Template);
10452 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
10453 }
10454
10455 return TemplateName(QTN);
10456}
10457
10458/// Retrieve the template name that represents a dependent
10459/// template name such as \c MetaFun::template operator+.
10462 llvm::FoldingSetNodeID ID;
10463 S.Profile(ID);
10464
10465 void *InsertPos = nullptr;
10466 if (DependentTemplateName *QTN =
10467 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos))
10468 return TemplateName(QTN);
10469
10471 new (*this, alignof(DependentTemplateName)) DependentTemplateName(S);
10472 DependentTemplateNames.InsertNode(QTN, InsertPos);
10473 return TemplateName(QTN);
10474}
10475
10477 Decl *AssociatedDecl,
10478 unsigned Index,
10479 UnsignedOrNone PackIndex,
10480 bool Final) const {
10481 llvm::FoldingSetNodeID ID;
10482 SubstTemplateTemplateParmStorage::Profile(ID, Replacement, AssociatedDecl,
10483 Index, PackIndex, Final);
10484
10485 void *insertPos = nullptr;
10487 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
10488
10489 if (!subst) {
10490 subst = new (*this) SubstTemplateTemplateParmStorage(
10491 Replacement, AssociatedDecl, Index, PackIndex, Final);
10492 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
10493 }
10494
10495 return TemplateName(subst);
10496}
10497
10500 Decl *AssociatedDecl,
10501 unsigned Index, bool Final) const {
10502 auto &Self = const_cast<ASTContext &>(*this);
10503 llvm::FoldingSetNodeID ID;
10505 AssociatedDecl, Index, Final);
10506
10507 void *InsertPos = nullptr;
10509 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
10510
10511 if (!Subst) {
10512 Subst = new (*this) SubstTemplateTemplateParmPackStorage(
10513 ArgPack.pack_elements(), AssociatedDecl, Index, Final);
10514 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
10515 }
10516
10517 return TemplateName(Subst);
10518}
10519
10520/// Retrieve the template name that represents a template name
10521/// deduced from a specialization.
10524 DefaultArguments DefaultArgs) const {
10525 if (!DefaultArgs)
10526 return Underlying;
10527
10528 llvm::FoldingSetNodeID ID;
10529 DeducedTemplateStorage::Profile(ID, *this, Underlying, DefaultArgs);
10530
10531 void *InsertPos = nullptr;
10533 DeducedTemplates.FindNodeOrInsertPos(ID, InsertPos);
10534 if (!DTS) {
10535 void *Mem = Allocate(sizeof(DeducedTemplateStorage) +
10536 sizeof(TemplateArgument) * DefaultArgs.Args.size(),
10537 alignof(DeducedTemplateStorage));
10538 DTS = new (Mem) DeducedTemplateStorage(Underlying, DefaultArgs);
10539 DeducedTemplates.InsertNode(DTS, InsertPos);
10540 }
10541 return TemplateName(DTS);
10542}
10543
10544/// getFromTargetType - Given one of the integer types provided by
10545/// TargetInfo, produce the corresponding type. The unsigned @p Type
10546/// is actually a value of type @c TargetInfo::IntType.
10547CanQualType ASTContext::getFromTargetType(unsigned Type) const {
10548 switch (Type) {
10549 case TargetInfo::NoInt: return {};
10552 case TargetInfo::SignedShort: return ShortTy;
10554 case TargetInfo::SignedInt: return IntTy;
10556 case TargetInfo::SignedLong: return LongTy;
10560 }
10561
10562 llvm_unreachable("Unhandled TargetInfo::IntType value");
10563}
10564
10565//===----------------------------------------------------------------------===//
10566// Type Predicates.
10567//===----------------------------------------------------------------------===//
10568
10569/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
10570/// garbage collection attribute.
10571///
10573 if (getLangOpts().getGC() == LangOptions::NonGC)
10574 return Qualifiers::GCNone;
10575
10576 assert(getLangOpts().ObjC);
10577 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
10578
10579 // Default behaviour under objective-C's gc is for ObjC pointers
10580 // (or pointers to them) be treated as though they were declared
10581 // as __strong.
10582 if (GCAttrs == Qualifiers::GCNone) {
10584 return Qualifiers::Strong;
10585 else if (Ty->isPointerType())
10587 } else {
10588 // It's not valid to set GC attributes on anything that isn't a
10589 // pointer.
10590#ifndef NDEBUG
10592 while (const auto *AT = dyn_cast<ArrayType>(CT))
10593 CT = AT->getElementType();
10594 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
10595#endif
10596 }
10597 return GCAttrs;
10598}
10599
10600//===----------------------------------------------------------------------===//
10601// Type Compatibility Testing
10602//===----------------------------------------------------------------------===//
10603
10604/// areCompatVectorTypes - Return true if the two specified vector types are
10605/// compatible.
10606static bool areCompatVectorTypes(const VectorType *LHS,
10607 const VectorType *RHS) {
10608 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10609 return LHS->getElementType() == RHS->getElementType() &&
10610 LHS->getNumElements() == RHS->getNumElements();
10611}
10612
10613/// areCompatMatrixTypes - Return true if the two specified matrix types are
10614/// compatible.
10616 const ConstantMatrixType *RHS) {
10617 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10618 return LHS->getElementType() == RHS->getElementType() &&
10619 LHS->getNumRows() == RHS->getNumRows() &&
10620 LHS->getNumColumns() == RHS->getNumColumns();
10621}
10622
10624 QualType SecondVec) {
10625 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
10626 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
10627
10628 if (hasSameUnqualifiedType(FirstVec, SecondVec))
10629 return true;
10630
10631 // Treat Neon vector types and most AltiVec vector types as if they are the
10632 // equivalent GCC vector types.
10633 const auto *First = FirstVec->castAs<VectorType>();
10634 const auto *Second = SecondVec->castAs<VectorType>();
10635 if (First->getNumElements() == Second->getNumElements() &&
10636 hasSameType(First->getElementType(), Second->getElementType()) &&
10637 First->getVectorKind() != VectorKind::AltiVecPixel &&
10638 First->getVectorKind() != VectorKind::AltiVecBool &&
10641 First->getVectorKind() != VectorKind::SveFixedLengthData &&
10642 First->getVectorKind() != VectorKind::SveFixedLengthPredicate &&
10645 First->getVectorKind() != VectorKind::RVVFixedLengthData &&
10647 First->getVectorKind() != VectorKind::RVVFixedLengthMask &&
10649 First->getVectorKind() != VectorKind::RVVFixedLengthMask_1 &&
10651 First->getVectorKind() != VectorKind::RVVFixedLengthMask_2 &&
10653 First->getVectorKind() != VectorKind::RVVFixedLengthMask_4 &&
10655 return true;
10656
10657 // In OpenCL, treat half and _Float16 vector types as compatible.
10658 if (getLangOpts().OpenCL &&
10659 First->getNumElements() == Second->getNumElements()) {
10660 QualType FirstElt = First->getElementType();
10661 QualType SecondElt = Second->getElementType();
10662
10663 if ((FirstElt->isFloat16Type() && SecondElt->isHalfType()) ||
10664 (FirstElt->isHalfType() && SecondElt->isFloat16Type())) {
10665 if (First->getVectorKind() != VectorKind::AltiVecPixel &&
10666 First->getVectorKind() != VectorKind::AltiVecBool &&
10669 return true;
10670 }
10671 }
10672 return false;
10673}
10674
10680
10683 const auto *LHSOBT = LHS->getAs<OverflowBehaviorType>();
10684 const auto *RHSOBT = RHS->getAs<OverflowBehaviorType>();
10685
10686 if (!LHSOBT && !RHSOBT)
10688
10689 if (LHSOBT && RHSOBT) {
10690 if (LHSOBT->getBehaviorKind() != RHSOBT->getBehaviorKind())
10693 }
10694
10695 QualType LHSUnderlying = LHSOBT ? LHSOBT->desugar() : LHS;
10696 QualType RHSUnderlying = RHSOBT ? RHSOBT->desugar() : RHS;
10697
10698 if (RHSOBT && !LHSOBT) {
10699 if (LHSUnderlying->isIntegerType() && RHSUnderlying->isIntegerType())
10701 }
10702
10704}
10705
10706/// getRVVTypeSize - Return RVV vector register size.
10707static uint64_t getRVVTypeSize(ASTContext &Context, const BuiltinType *Ty) {
10708 assert(Ty->isRVVVLSBuiltinType() && "Invalid RVV Type");
10709 auto VScale = Context.getTargetInfo().getVScaleRange(
10710 Context.getLangOpts(), TargetInfo::ArmStreamingKind::NotStreaming);
10711 if (!VScale)
10712 return 0;
10713
10714 ASTContext::BuiltinVectorTypeInfo Info = Context.getBuiltinVectorTypeInfo(Ty);
10715
10716 uint64_t EltSize = Context.getTypeSize(Info.ElementType);
10717 if (Info.ElementType == Context.BoolTy)
10718 EltSize = 1;
10719
10720 uint64_t MinElts = Info.EC.getKnownMinValue();
10721 return VScale->first * MinElts * EltSize;
10722}
10723
10725 QualType SecondType) {
10726 assert(
10727 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10728 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10729 "Expected RVV builtin type and vector type!");
10730
10731 auto IsValidCast = [this](QualType FirstType, QualType SecondType) {
10732 if (const auto *BT = FirstType->getAs<BuiltinType>()) {
10733 if (const auto *VT = SecondType->getAs<VectorType>()) {
10734 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask) {
10736 return FirstType->isRVVVLSBuiltinType() &&
10737 Info.ElementType == BoolTy &&
10738 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)));
10739 }
10740 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_1) {
10742 return FirstType->isRVVVLSBuiltinType() &&
10743 Info.ElementType == BoolTy &&
10744 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT) * 8));
10745 }
10746 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_2) {
10748 return FirstType->isRVVVLSBuiltinType() &&
10749 Info.ElementType == BoolTy &&
10750 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)) * 4);
10751 }
10752 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_4) {
10754 return FirstType->isRVVVLSBuiltinType() &&
10755 Info.ElementType == BoolTy &&
10756 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)) * 2);
10757 }
10758 if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
10759 VT->getVectorKind() == VectorKind::Generic)
10760 return FirstType->isRVVVLSBuiltinType() &&
10761 getTypeSize(SecondType) == getRVVTypeSize(*this, BT) &&
10762 hasSameType(VT->getElementType(),
10763 getBuiltinVectorTypeInfo(BT).ElementType);
10764 }
10765 }
10766 return false;
10767 };
10768
10769 return IsValidCast(FirstType, SecondType) ||
10770 IsValidCast(SecondType, FirstType);
10771}
10772
10774 QualType SecondType) {
10775 assert(
10776 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10777 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10778 "Expected RVV builtin type and vector type!");
10779
10780 auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) {
10781 const auto *BT = FirstType->getAs<BuiltinType>();
10782 if (!BT)
10783 return false;
10784
10785 if (!BT->isRVVVLSBuiltinType())
10786 return false;
10787
10788 const auto *VecTy = SecondType->getAs<VectorType>();
10789 if (VecTy && VecTy->getVectorKind() == VectorKind::Generic) {
10791 getLangOpts().getLaxVectorConversions();
10792
10793 // If __riscv_v_fixed_vlen != N do not allow vector lax conversion.
10794 if (getTypeSize(SecondType) != getRVVTypeSize(*this, BT))
10795 return false;
10796
10797 // If -flax-vector-conversions=all is specified, the types are
10798 // certainly compatible.
10800 return true;
10801
10802 // If -flax-vector-conversions=integer is specified, the types are
10803 // compatible if the elements are integer types.
10805 return VecTy->getElementType().getCanonicalType()->isIntegerType() &&
10806 FirstType->getRVVEltType(*this)->isIntegerType();
10807 }
10808
10809 return false;
10810 };
10811
10812 return IsLaxCompatible(FirstType, SecondType) ||
10813 IsLaxCompatible(SecondType, FirstType);
10814}
10815
10817 while (true) {
10818 // __strong id
10819 if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) {
10820 if (Attr->getAttrKind() == attr::ObjCOwnership)
10821 return true;
10822
10823 Ty = Attr->getModifiedType();
10824
10825 // X *__strong (...)
10826 } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) {
10827 Ty = Paren->getInnerType();
10828
10829 // We do not want to look through typedefs, typeof(expr),
10830 // typeof(type), or any other way that the type is somehow
10831 // abstracted.
10832 } else {
10833 return false;
10834 }
10835 }
10836}
10837
10838//===----------------------------------------------------------------------===//
10839// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
10840//===----------------------------------------------------------------------===//
10841
10842/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
10843/// inheritance hierarchy of 'rProto'.
10844bool
10846 ObjCProtocolDecl *rProto) const {
10847 if (declaresSameEntity(lProto, rProto))
10848 return true;
10849 for (auto *PI : rProto->protocols())
10850 if (ProtocolCompatibleWithProtocol(lProto, PI))
10851 return true;
10852 return false;
10853}
10854
10855/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
10856/// Class<pr1, ...>.
10858 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) {
10859 for (auto *lhsProto : lhs->quals()) {
10860 bool match = false;
10861 for (auto *rhsProto : rhs->quals()) {
10862 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
10863 match = true;
10864 break;
10865 }
10866 }
10867 if (!match)
10868 return false;
10869 }
10870 return true;
10871}
10872
10873/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
10874/// ObjCQualifiedIDType.
10876 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs,
10877 bool compare) {
10878 // Allow id<P..> and an 'id' in all cases.
10879 if (lhs->isObjCIdType() || rhs->isObjCIdType())
10880 return true;
10881
10882 // Don't allow id<P..> to convert to Class or Class<P..> in either direction.
10883 if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() ||
10885 return false;
10886
10887 if (lhs->isObjCQualifiedIdType()) {
10888 if (rhs->qual_empty()) {
10889 // If the RHS is a unqualified interface pointer "NSString*",
10890 // make sure we check the class hierarchy.
10891 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
10892 for (auto *I : lhs->quals()) {
10893 // when comparing an id<P> on lhs with a static type on rhs,
10894 // see if static class implements all of id's protocols, directly or
10895 // through its super class and categories.
10896 if (!rhsID->ClassImplementsProtocol(I, true))
10897 return false;
10898 }
10899 }
10900 // If there are no qualifiers and no interface, we have an 'id'.
10901 return true;
10902 }
10903 // Both the right and left sides have qualifiers.
10904 for (auto *lhsProto : lhs->quals()) {
10905 bool match = false;
10906
10907 // when comparing an id<P> on lhs with a static type on rhs,
10908 // see if static class implements all of id's protocols, directly or
10909 // through its super class and categories.
10910 for (auto *rhsProto : rhs->quals()) {
10911 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
10912 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
10913 match = true;
10914 break;
10915 }
10916 }
10917 // If the RHS is a qualified interface pointer "NSString<P>*",
10918 // make sure we check the class hierarchy.
10919 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
10920 for (auto *I : lhs->quals()) {
10921 // when comparing an id<P> on lhs with a static type on rhs,
10922 // see if static class implements all of id's protocols, directly or
10923 // through its super class and categories.
10924 if (rhsID->ClassImplementsProtocol(I, true)) {
10925 match = true;
10926 break;
10927 }
10928 }
10929 }
10930 if (!match)
10931 return false;
10932 }
10933
10934 return true;
10935 }
10936
10937 assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>");
10938
10939 if (lhs->getInterfaceType()) {
10940 // If both the right and left sides have qualifiers.
10941 for (auto *lhsProto : lhs->quals()) {
10942 bool match = false;
10943
10944 // when comparing an id<P> on rhs with a static type on lhs,
10945 // see if static class implements all of id's protocols, directly or
10946 // through its super class and categories.
10947 // First, lhs protocols in the qualifier list must be found, direct
10948 // or indirect in rhs's qualifier list or it is a mismatch.
10949 for (auto *rhsProto : rhs->quals()) {
10950 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
10951 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
10952 match = true;
10953 break;
10954 }
10955 }
10956 if (!match)
10957 return false;
10958 }
10959
10960 // Static class's protocols, or its super class or category protocols
10961 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
10962 if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) {
10963 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
10964 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
10965 // This is rather dubious but matches gcc's behavior. If lhs has
10966 // no type qualifier and its class has no static protocol(s)
10967 // assume that it is mismatch.
10968 if (LHSInheritedProtocols.empty() && lhs->qual_empty())
10969 return false;
10970 for (auto *lhsProto : LHSInheritedProtocols) {
10971 bool match = false;
10972 for (auto *rhsProto : rhs->quals()) {
10973 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
10974 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
10975 match = true;
10976 break;
10977 }
10978 }
10979 if (!match)
10980 return false;
10981 }
10982 }
10983 return true;
10984 }
10985 return false;
10986}
10987
10988/// canAssignObjCInterfaces - Return true if the two interface types are
10989/// compatible for assignment from RHS to LHS. This handles validation of any
10990/// protocol qualifiers on the LHS or RHS.
10992 const ObjCObjectPointerType *RHSOPT) {
10993 const ObjCObjectType* LHS = LHSOPT->getObjectType();
10994 const ObjCObjectType* RHS = RHSOPT->getObjectType();
10995
10996 // If either type represents the built-in 'id' type, return true.
10997 if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId())
10998 return true;
10999
11000 // Function object that propagates a successful result or handles
11001 // __kindof types.
11002 auto finish = [&](bool succeeded) -> bool {
11003 if (succeeded)
11004 return true;
11005
11006 if (!RHS->isKindOfType())
11007 return false;
11008
11009 // Strip off __kindof and protocol qualifiers, then check whether
11010 // we can assign the other way.
11012 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
11013 };
11014
11015 // Casts from or to id<P> are allowed when the other side has compatible
11016 // protocols.
11017 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
11018 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false));
11019 }
11020
11021 // Verify protocol compatibility for casts from Class<P1> to Class<P2>.
11022 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
11023 return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT));
11024 }
11025
11026 // Casts from Class to Class<Foo>, or vice-versa, are allowed.
11027 if (LHS->isObjCClass() && RHS->isObjCClass()) {
11028 return true;
11029 }
11030
11031 // If we have 2 user-defined types, fall into that path.
11032 if (LHS->getInterface() && RHS->getInterface()) {
11033 return finish(canAssignObjCInterfaces(LHS, RHS));
11034 }
11035
11036 return false;
11037}
11038
11039/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
11040/// for providing type-safety for objective-c pointers used to pass/return
11041/// arguments in block literals. When passed as arguments, passing 'A*' where
11042/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
11043/// not OK. For the return type, the opposite is not OK.
11045 const ObjCObjectPointerType *LHSOPT,
11046 const ObjCObjectPointerType *RHSOPT,
11047 bool BlockReturnType) {
11048
11049 // Function object that propagates a successful result or handles
11050 // __kindof types.
11051 auto finish = [&](bool succeeded) -> bool {
11052 if (succeeded)
11053 return true;
11054
11055 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
11056 if (!Expected->isKindOfType())
11057 return false;
11058
11059 // Strip off __kindof and protocol qualifiers, then check whether
11060 // we can assign the other way.
11062 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
11063 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
11064 BlockReturnType);
11065 };
11066
11067 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
11068 return true;
11069
11070 if (LHSOPT->isObjCBuiltinType()) {
11071 return finish(RHSOPT->isObjCBuiltinType() ||
11072 RHSOPT->isObjCQualifiedIdType());
11073 }
11074
11075 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) {
11076 if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking)
11077 // Use for block parameters previous type checking for compatibility.
11078 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false) ||
11079 // Or corrected type checking as in non-compat mode.
11080 (!BlockReturnType &&
11081 ObjCQualifiedIdTypesAreCompatible(RHSOPT, LHSOPT, false)));
11082 else
11084 (BlockReturnType ? LHSOPT : RHSOPT),
11085 (BlockReturnType ? RHSOPT : LHSOPT), false));
11086 }
11087
11088 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
11089 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
11090 if (LHS && RHS) { // We have 2 user-defined types.
11091 if (LHS != RHS) {
11092 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
11093 return finish(BlockReturnType);
11094 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
11095 return finish(!BlockReturnType);
11096 }
11097 else
11098 return true;
11099 }
11100 return false;
11101}
11102
11103/// Comparison routine for Objective-C protocols to be used with
11104/// llvm::array_pod_sort.
11106 ObjCProtocolDecl * const *rhs) {
11107 return (*lhs)->getName().compare((*rhs)->getName());
11108}
11109
11110/// getIntersectionOfProtocols - This routine finds the intersection of set
11111/// of protocols inherited from two distinct objective-c pointer objects with
11112/// the given common base.
11113/// It is used to build composite qualifier list of the composite type of
11114/// the conditional expression involving two objective-c pointer objects.
11115static
11117 const ObjCInterfaceDecl *CommonBase,
11118 const ObjCObjectPointerType *LHSOPT,
11119 const ObjCObjectPointerType *RHSOPT,
11120 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
11121
11122 const ObjCObjectType* LHS = LHSOPT->getObjectType();
11123 const ObjCObjectType* RHS = RHSOPT->getObjectType();
11124 assert(LHS->getInterface() && "LHS must have an interface base");
11125 assert(RHS->getInterface() && "RHS must have an interface base");
11126
11127 // Add all of the protocols for the LHS.
11129
11130 // Start with the protocol qualifiers.
11131 for (auto *proto : LHS->quals()) {
11132 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
11133 }
11134
11135 // Also add the protocols associated with the LHS interface.
11136 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
11137
11138 // Add all of the protocols for the RHS.
11140
11141 // Start with the protocol qualifiers.
11142 for (auto *proto : RHS->quals()) {
11143 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
11144 }
11145
11146 // Also add the protocols associated with the RHS interface.
11147 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
11148
11149 // Compute the intersection of the collected protocol sets.
11150 for (auto *proto : LHSProtocolSet) {
11151 if (RHSProtocolSet.count(proto))
11152 IntersectionSet.push_back(proto);
11153 }
11154
11155 // Compute the set of protocols that is implied by either the common type or
11156 // the protocols within the intersection.
11158 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
11159
11160 // Remove any implied protocols from the list of inherited protocols.
11161 if (!ImpliedProtocols.empty()) {
11162 llvm::erase_if(IntersectionSet, [&](ObjCProtocolDecl *proto) -> bool {
11163 return ImpliedProtocols.contains(proto);
11164 });
11165 }
11166
11167 // Sort the remaining protocols by name.
11168 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
11170}
11171
11172/// Determine whether the first type is a subtype of the second.
11174 QualType rhs) {
11175 // Common case: two object pointers.
11176 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
11177 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
11178 if (lhsOPT && rhsOPT)
11179 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
11180
11181 // Two block pointers.
11182 const auto *lhsBlock = lhs->getAs<BlockPointerType>();
11183 const auto *rhsBlock = rhs->getAs<BlockPointerType>();
11184 if (lhsBlock && rhsBlock)
11185 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
11186
11187 // If either is an unqualified 'id' and the other is a block, it's
11188 // acceptable.
11189 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
11190 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
11191 return true;
11192
11193 return false;
11194}
11195
11196// Check that the given Objective-C type argument lists are equivalent.
11198 const ObjCInterfaceDecl *iface,
11199 ArrayRef<QualType> lhsArgs,
11200 ArrayRef<QualType> rhsArgs,
11201 bool stripKindOf) {
11202 if (lhsArgs.size() != rhsArgs.size())
11203 return false;
11204
11205 ObjCTypeParamList *typeParams = iface->getTypeParamList();
11206 if (!typeParams)
11207 return false;
11208
11209 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
11210 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
11211 continue;
11212
11213 switch (typeParams->begin()[i]->getVariance()) {
11215 if (!stripKindOf ||
11216 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
11217 rhsArgs[i].stripObjCKindOfType(ctx))) {
11218 return false;
11219 }
11220 break;
11221
11223 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
11224 return false;
11225 break;
11226
11228 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
11229 return false;
11230 break;
11231 }
11232 }
11233
11234 return true;
11235}
11236
11238 const ObjCObjectPointerType *Lptr,
11239 const ObjCObjectPointerType *Rptr) {
11240 const ObjCObjectType *LHS = Lptr->getObjectType();
11241 const ObjCObjectType *RHS = Rptr->getObjectType();
11242 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
11243 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
11244
11245 if (!LDecl || !RDecl)
11246 return {};
11247
11248 // When either LHS or RHS is a kindof type, we should return a kindof type.
11249 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
11250 // kindof(A).
11251 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
11252
11253 // Follow the left-hand side up the class hierarchy until we either hit a
11254 // root or find the RHS. Record the ancestors in case we don't find it.
11255 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
11256 LHSAncestors;
11257 while (true) {
11258 // Record this ancestor. We'll need this if the common type isn't in the
11259 // path from the LHS to the root.
11260 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
11261
11262 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
11263 // Get the type arguments.
11264 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
11265 bool anyChanges = false;
11266 if (LHS->isSpecialized() && RHS->isSpecialized()) {
11267 // Both have type arguments, compare them.
11268 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
11269 LHS->getTypeArgs(), RHS->getTypeArgs(),
11270 /*stripKindOf=*/true))
11271 return {};
11272 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
11273 // If only one has type arguments, the result will not have type
11274 // arguments.
11275 LHSTypeArgs = {};
11276 anyChanges = true;
11277 }
11278
11279 // Compute the intersection of protocols.
11281 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
11282 Protocols);
11283 if (!Protocols.empty())
11284 anyChanges = true;
11285
11286 // If anything in the LHS will have changed, build a new result type.
11287 // If we need to return a kindof type but LHS is not a kindof type, we
11288 // build a new result type.
11289 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
11290 QualType Result = getObjCInterfaceType(LHS->getInterface());
11291 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
11292 anyKindOf || LHS->isKindOfType());
11294 }
11295
11296 return getObjCObjectPointerType(QualType(LHS, 0));
11297 }
11298
11299 // Find the superclass.
11300 QualType LHSSuperType = LHS->getSuperClassType();
11301 if (LHSSuperType.isNull())
11302 break;
11303
11304 LHS = LHSSuperType->castAs<ObjCObjectType>();
11305 }
11306
11307 // We didn't find anything by following the LHS to its root; now check
11308 // the RHS against the cached set of ancestors.
11309 while (true) {
11310 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
11311 if (KnownLHS != LHSAncestors.end()) {
11312 LHS = KnownLHS->second;
11313
11314 // Get the type arguments.
11315 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
11316 bool anyChanges = false;
11317 if (LHS->isSpecialized() && RHS->isSpecialized()) {
11318 // Both have type arguments, compare them.
11319 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
11320 LHS->getTypeArgs(), RHS->getTypeArgs(),
11321 /*stripKindOf=*/true))
11322 return {};
11323 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
11324 // If only one has type arguments, the result will not have type
11325 // arguments.
11326 RHSTypeArgs = {};
11327 anyChanges = true;
11328 }
11329
11330 // Compute the intersection of protocols.
11332 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
11333 Protocols);
11334 if (!Protocols.empty())
11335 anyChanges = true;
11336
11337 // If we need to return a kindof type but RHS is not a kindof type, we
11338 // build a new result type.
11339 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
11340 QualType Result = getObjCInterfaceType(RHS->getInterface());
11341 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
11342 anyKindOf || RHS->isKindOfType());
11344 }
11345
11346 return getObjCObjectPointerType(QualType(RHS, 0));
11347 }
11348
11349 // Find the superclass of the RHS.
11350 QualType RHSSuperType = RHS->getSuperClassType();
11351 if (RHSSuperType.isNull())
11352 break;
11353
11354 RHS = RHSSuperType->castAs<ObjCObjectType>();
11355 }
11356
11357 return {};
11358}
11359
11361 const ObjCObjectType *RHS) {
11362 assert(LHS->getInterface() && "LHS is not an interface type");
11363 assert(RHS->getInterface() && "RHS is not an interface type");
11364
11365 // Verify that the base decls are compatible: the RHS must be a subclass of
11366 // the LHS.
11367 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
11368 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
11369 if (!IsSuperClass)
11370 return false;
11371
11372 // If the LHS has protocol qualifiers, determine whether all of them are
11373 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
11374 // LHS).
11375 if (LHS->getNumProtocols() > 0) {
11376 // OK if conversion of LHS to SuperClass results in narrowing of types
11377 // ; i.e., SuperClass may implement at least one of the protocols
11378 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
11379 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
11380 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
11381 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
11382 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
11383 // qualifiers.
11384 for (auto *RHSPI : RHS->quals())
11385 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
11386 // If there is no protocols associated with RHS, it is not a match.
11387 if (SuperClassInheritedProtocols.empty())
11388 return false;
11389
11390 for (const auto *LHSProto : LHS->quals()) {
11391 bool SuperImplementsProtocol = false;
11392 for (auto *SuperClassProto : SuperClassInheritedProtocols)
11393 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
11394 SuperImplementsProtocol = true;
11395 break;
11396 }
11397 if (!SuperImplementsProtocol)
11398 return false;
11399 }
11400 }
11401
11402 // If the LHS is specialized, we may need to check type arguments.
11403 if (LHS->isSpecialized()) {
11404 // Follow the superclass chain until we've matched the LHS class in the
11405 // hierarchy. This substitutes type arguments through.
11406 const ObjCObjectType *RHSSuper = RHS;
11407 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
11408 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
11409
11410 // If the RHS is specializd, compare type arguments.
11411 if (RHSSuper->isSpecialized() &&
11412 !sameObjCTypeArgs(*this, LHS->getInterface(),
11413 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
11414 /*stripKindOf=*/true)) {
11415 return false;
11416 }
11417 }
11418
11419 return true;
11420}
11421
11423 // get the "pointed to" types
11424 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
11425 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
11426
11427 if (!LHSOPT || !RHSOPT)
11428 return false;
11429
11430 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
11431 canAssignObjCInterfaces(RHSOPT, LHSOPT);
11432}
11433
11436 getObjCObjectPointerType(To)->castAs<ObjCObjectPointerType>(),
11437 getObjCObjectPointerType(From)->castAs<ObjCObjectPointerType>());
11438}
11439
11440/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
11441/// both shall have the identically qualified version of a compatible type.
11442/// C99 6.2.7p1: Two types have compatible types if their types are the
11443/// same. See 6.7.[2,3,5] for additional rules.
11445 bool CompareUnqualified) {
11446 if (getLangOpts().CPlusPlus)
11447 return hasSameType(LHS, RHS);
11448
11449 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
11450}
11451
11453 return typesAreCompatible(LHS, RHS);
11454}
11455
11457 return !mergeTypes(LHS, RHS, true).isNull();
11458}
11459
11460/// mergeTransparentUnionType - if T is a transparent union type and a member
11461/// of T is compatible with SubType, return the merged type, else return
11462/// QualType()
11464 bool OfBlockPointer,
11465 bool Unqualified) {
11466 if (const RecordType *UT = T->getAsUnionType()) {
11467 RecordDecl *UD = UT->getDecl()->getMostRecentDecl();
11468 if (UD->hasAttr<TransparentUnionAttr>()) {
11469 for (const auto *I : UD->fields()) {
11470 QualType ET = I->getType().getUnqualifiedType();
11471 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
11472 if (!MT.isNull())
11473 return MT;
11474 }
11475 }
11476 }
11477
11478 return {};
11479}
11480
11481/// mergeFunctionParameterTypes - merge two types which appear as function
11482/// parameter types
11484 bool OfBlockPointer,
11485 bool Unqualified) {
11486 // GNU extension: two types are compatible if they appear as a function
11487 // argument, one of the types is a transparent union type and the other
11488 // type is compatible with a union member
11489 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
11490 Unqualified);
11491 if (!lmerge.isNull())
11492 return lmerge;
11493
11494 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
11495 Unqualified);
11496 if (!rmerge.isNull())
11497 return rmerge;
11498
11499 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
11500}
11501
11503 bool OfBlockPointer, bool Unqualified,
11504 bool AllowCXX,
11505 bool IsConditionalOperator) {
11506 const auto *lbase = lhs->castAs<FunctionType>();
11507 const auto *rbase = rhs->castAs<FunctionType>();
11508 const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
11509 const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
11510 bool allLTypes = true;
11511 bool allRTypes = true;
11512
11513 // Check return type
11514 QualType retType;
11515 if (OfBlockPointer) {
11516 QualType RHS = rbase->getReturnType();
11517 QualType LHS = lbase->getReturnType();
11518 bool UnqualifiedResult = Unqualified;
11519 if (!UnqualifiedResult)
11520 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
11521 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
11522 }
11523 else
11524 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
11525 Unqualified);
11526 if (retType.isNull())
11527 return {};
11528
11529 if (Unqualified)
11530 retType = retType.getUnqualifiedType();
11531
11532 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
11533 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
11534 if (Unqualified) {
11535 LRetType = LRetType.getUnqualifiedType();
11536 RRetType = RRetType.getUnqualifiedType();
11537 }
11538
11539 if (getCanonicalType(retType) != LRetType)
11540 allLTypes = false;
11541 if (getCanonicalType(retType) != RRetType)
11542 allRTypes = false;
11543
11544 // FIXME: double check this
11545 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
11546 // rbase->getRegParmAttr() != 0 &&
11547 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
11548 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
11549 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
11550
11551 // Compatible functions must have compatible calling conventions
11552 if (lbaseInfo.getCC() != rbaseInfo.getCC())
11553 return {};
11554
11555 // Regparm is part of the calling convention.
11556 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
11557 return {};
11558 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
11559 return {};
11560
11561 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
11562 return {};
11563 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
11564 return {};
11565 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
11566 return {};
11567
11568 // When merging declarations, it's common for supplemental information like
11569 // attributes to only be present in one of the declarations, and we generally
11570 // want type merging to preserve the union of information. So a merged
11571 // function type should be noreturn if it was noreturn in *either* operand
11572 // type.
11573 //
11574 // But for the conditional operator, this is backwards. The result of the
11575 // operator could be either operand, and its type should conservatively
11576 // reflect that. So a function type in a composite type is noreturn only
11577 // if it's noreturn in *both* operand types.
11578 //
11579 // Arguably, noreturn is a kind of subtype, and the conditional operator
11580 // ought to produce the most specific common supertype of its operand types.
11581 // That would differ from this rule in contravariant positions. However,
11582 // neither C nor C++ generally uses this kind of subtype reasoning. Also,
11583 // as a practical matter, it would only affect C code that does abstraction of
11584 // higher-order functions (taking noreturn callbacks!), which is uncommon to
11585 // say the least. So we use the simpler rule.
11586 bool NoReturn = IsConditionalOperator
11587 ? lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn()
11588 : lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
11589 if (lbaseInfo.getNoReturn() != NoReturn)
11590 allLTypes = false;
11591 if (rbaseInfo.getNoReturn() != NoReturn)
11592 allRTypes = false;
11593
11594 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
11595
11596 std::optional<FunctionEffectSet> MergedFX;
11597
11598 if (lproto && rproto) { // two C99 style function prototypes
11599 assert((AllowCXX ||
11600 (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) &&
11601 "C++ shouldn't be here");
11602 // Compatible functions must have the same number of parameters
11603 if (lproto->getNumParams() != rproto->getNumParams())
11604 return {};
11605
11606 // Variadic and non-variadic functions aren't compatible
11607 if (lproto->isVariadic() != rproto->isVariadic())
11608 return {};
11609
11610 if (lproto->getMethodQuals() != rproto->getMethodQuals())
11611 return {};
11612
11613 // Function protos with different 'cfi_salt' values aren't compatible.
11614 if (lproto->getExtraAttributeInfo().CFISalt !=
11615 rproto->getExtraAttributeInfo().CFISalt)
11616 return {};
11617
11618 // Function effects are handled similarly to noreturn, see above.
11619 FunctionEffectsRef LHSFX = lproto->getFunctionEffects();
11620 FunctionEffectsRef RHSFX = rproto->getFunctionEffects();
11621 if (LHSFX != RHSFX) {
11622 if (IsConditionalOperator)
11623 MergedFX = FunctionEffectSet::getIntersection(LHSFX, RHSFX);
11624 else {
11626 MergedFX = FunctionEffectSet::getUnion(LHSFX, RHSFX, Errs);
11627 // Here we're discarding a possible error due to conflicts in the effect
11628 // sets. But we're not in a context where we can report it. The
11629 // operation does however guarantee maintenance of invariants.
11630 }
11631 if (*MergedFX != LHSFX)
11632 allLTypes = false;
11633 if (*MergedFX != RHSFX)
11634 allRTypes = false;
11635 }
11636
11638 bool canUseLeft, canUseRight;
11639 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
11640 newParamInfos))
11641 return {};
11642
11643 if (!canUseLeft)
11644 allLTypes = false;
11645 if (!canUseRight)
11646 allRTypes = false;
11647
11648 // Check parameter type compatibility
11650 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
11651 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
11652 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
11654 lParamType, rParamType, OfBlockPointer, Unqualified);
11655 if (paramType.isNull())
11656 return {};
11657
11658 if (Unqualified)
11659 paramType = paramType.getUnqualifiedType();
11660
11661 types.push_back(paramType);
11662 if (Unqualified) {
11663 lParamType = lParamType.getUnqualifiedType();
11664 rParamType = rParamType.getUnqualifiedType();
11665 }
11666
11667 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
11668 allLTypes = false;
11669 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
11670 allRTypes = false;
11671 }
11672
11673 if (allLTypes) return lhs;
11674 if (allRTypes) return rhs;
11675
11676 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
11677 EPI.ExtInfo = einfo;
11678 EPI.ExtParameterInfos =
11679 newParamInfos.empty() ? nullptr : newParamInfos.data();
11680 if (MergedFX)
11681 EPI.FunctionEffects = *MergedFX;
11682 return getFunctionType(retType, types, EPI);
11683 }
11684
11685 if (lproto) allRTypes = false;
11686 if (rproto) allLTypes = false;
11687
11688 const FunctionProtoType *proto = lproto ? lproto : rproto;
11689 if (proto) {
11690 assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here");
11691 if (proto->isVariadic())
11692 return {};
11693 // Check that the types are compatible with the types that
11694 // would result from default argument promotions (C99 6.7.5.3p15).
11695 // The only types actually affected are promotable integer
11696 // types and floats, which would be passed as a different
11697 // type depending on whether the prototype is visible.
11698 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
11699 QualType paramTy = proto->getParamType(i);
11700
11701 // Look at the converted type of enum types, since that is the type used
11702 // to pass enum values.
11703 if (const auto *ED = paramTy->getAsEnumDecl()) {
11704 paramTy = ED->getIntegerType();
11705 if (paramTy.isNull())
11706 return {};
11707 }
11708
11709 if (isPromotableIntegerType(paramTy) ||
11710 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
11711 return {};
11712 }
11713
11714 if (allLTypes) return lhs;
11715 if (allRTypes) return rhs;
11716
11718 EPI.ExtInfo = einfo;
11719 if (MergedFX)
11720 EPI.FunctionEffects = *MergedFX;
11721 return getFunctionType(retType, proto->getParamTypes(), EPI);
11722 }
11723
11724 if (allLTypes) return lhs;
11725 if (allRTypes) return rhs;
11726 return getFunctionNoProtoType(retType, einfo);
11727}
11728
11729/// Given that we have an enum type and a non-enum type, try to merge them.
11730static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
11731 QualType other, bool isBlockReturnType) {
11732 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
11733 // a signed integer type, or an unsigned integer type.
11734 // Compatibility is based on the underlying type, not the promotion
11735 // type.
11736 QualType underlyingType =
11737 ET->getDecl()->getDefinitionOrSelf()->getIntegerType();
11738 if (underlyingType.isNull())
11739 return {};
11740 if (Context.hasSameType(underlyingType, other))
11741 return other;
11742
11743 // In block return types, we're more permissive and accept any
11744 // integral type of the same size.
11745 if (isBlockReturnType && other->isIntegerType() &&
11746 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
11747 return other;
11748
11749 return {};
11750}
11751
11753 // C17 and earlier and C++ disallow two tag definitions within the same TU
11754 // from being compatible.
11755 if (LangOpts.CPlusPlus || !LangOpts.C23)
11756 return {};
11757
11758 // Nameless tags are comparable only within outer definitions. At the top
11759 // level they are not comparable.
11760 const TagDecl *LTagD = LHS->castAsTagDecl(), *RTagD = RHS->castAsTagDecl();
11761 if (!LTagD->getIdentifier() || !RTagD->getIdentifier())
11762 return {};
11763
11764 // C23, on the other hand, requires the members to be "the same enough", so
11765 // we use a structural equivalence check.
11768 getLangOpts(), *this, *this, NonEquivalentDecls,
11769 StructuralEquivalenceKind::Default, /*StrictTypeSpelling=*/false,
11770 /*Complain=*/false, /*ErrorOnTagTypeMismatch=*/true);
11771 return Ctx.IsEquivalent(LHS, RHS) ? LHS : QualType{};
11772}
11773
11775 QualType LHS, QualType RHS, bool OfBlockPointer, bool Unqualified,
11776 bool BlockReturnType, bool IsConditionalOperator) {
11777 const auto *LHSOBT = LHS->getAs<OverflowBehaviorType>();
11778 const auto *RHSOBT = RHS->getAs<OverflowBehaviorType>();
11779
11780 if (!LHSOBT && !RHSOBT)
11781 return std::nullopt;
11782
11783 if (LHSOBT) {
11784 if (RHSOBT) {
11785 if (LHSOBT->getBehaviorKind() != RHSOBT->getBehaviorKind())
11786 return QualType();
11787
11788 QualType MergedUnderlying = mergeTypes(
11789 LHSOBT->getUnderlyingType(), RHSOBT->getUnderlyingType(),
11790 OfBlockPointer, Unqualified, BlockReturnType, IsConditionalOperator);
11791
11792 if (MergedUnderlying.isNull())
11793 return QualType();
11794
11795 if (getCanonicalType(LHSOBT) == getCanonicalType(RHSOBT)) {
11796 if (LHSOBT->getUnderlyingType() == RHSOBT->getUnderlyingType())
11797 return getCommonSugaredType(LHS, RHS);
11799 LHSOBT->getBehaviorKind(),
11800 getCanonicalType(LHSOBT->getUnderlyingType()));
11801 }
11802
11803 // For different underlying types that successfully merge, wrap the
11804 // merged underlying type with the common overflow behavior
11805 return getOverflowBehaviorType(LHSOBT->getBehaviorKind(),
11806 MergedUnderlying);
11807 }
11808 return mergeTypes(LHSOBT->getUnderlyingType(), RHS, OfBlockPointer,
11809 Unqualified, BlockReturnType, IsConditionalOperator);
11810 }
11811
11812 return mergeTypes(LHS, RHSOBT->getUnderlyingType(), OfBlockPointer,
11813 Unqualified, BlockReturnType, IsConditionalOperator);
11814}
11815
11816QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
11817 bool Unqualified, bool BlockReturnType,
11818 bool IsConditionalOperator) {
11819 // For C++ we will not reach this code with reference types (see below),
11820 // for OpenMP variant call overloading we might.
11821 //
11822 // C++ [expr]: If an expression initially has the type "reference to T", the
11823 // type is adjusted to "T" prior to any further analysis, the expression
11824 // designates the object or function denoted by the reference, and the
11825 // expression is an lvalue unless the reference is an rvalue reference and
11826 // the expression is a function call (possibly inside parentheses).
11827 auto *LHSRefTy = LHS->getAs<ReferenceType>();
11828 auto *RHSRefTy = RHS->getAs<ReferenceType>();
11829 if (LangOpts.OpenMP && LHSRefTy && RHSRefTy &&
11830 LHS->getTypeClass() == RHS->getTypeClass())
11831 return mergeTypes(LHSRefTy->getPointeeType(), RHSRefTy->getPointeeType(),
11832 OfBlockPointer, Unqualified, BlockReturnType);
11833 if (LHSRefTy || RHSRefTy)
11834 return {};
11835
11836 if (std::optional<QualType> MergedOBT =
11837 tryMergeOverflowBehaviorTypes(LHS, RHS, OfBlockPointer, Unqualified,
11838 BlockReturnType, IsConditionalOperator))
11839 return *MergedOBT;
11840
11841 if (Unqualified) {
11842 LHS = LHS.getUnqualifiedType();
11843 RHS = RHS.getUnqualifiedType();
11844 }
11845
11846 QualType LHSCan = getCanonicalType(LHS),
11847 RHSCan = getCanonicalType(RHS);
11848
11849 // If two types are identical, they are compatible.
11850 if (LHSCan == RHSCan)
11851 return LHS;
11852
11853 // If the qualifiers are different, the types aren't compatible... mostly.
11854 Qualifiers LQuals = LHSCan.getLocalQualifiers();
11855 Qualifiers RQuals = RHSCan.getLocalQualifiers();
11856 if (LQuals != RQuals) {
11857 // If any of these qualifiers are different, we have a type
11858 // mismatch.
11859 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
11860 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
11861 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
11862 !LQuals.getPointerAuth().isEquivalent(RQuals.getPointerAuth()) ||
11863 LQuals.hasUnaligned() != RQuals.hasUnaligned())
11864 return {};
11865
11866 // Exactly one GC qualifier difference is allowed: __strong is
11867 // okay if the other type has no GC qualifier but is an Objective
11868 // C object pointer (i.e. implicitly strong by default). We fix
11869 // this by pretending that the unqualified type was actually
11870 // qualified __strong.
11871 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
11872 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
11873 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
11874
11875 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
11876 return {};
11877
11878 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
11880 }
11881 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
11883 }
11884 return {};
11885 }
11886
11887 // Okay, qualifiers are equal.
11888
11889 Type::TypeClass LHSClass = LHSCan->getTypeClass();
11890 Type::TypeClass RHSClass = RHSCan->getTypeClass();
11891
11892 // We want to consider the two function types to be the same for these
11893 // comparisons, just force one to the other.
11894 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
11895 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
11896
11897 // Same as above for arrays
11898 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
11899 LHSClass = Type::ConstantArray;
11900 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
11901 RHSClass = Type::ConstantArray;
11902
11903 // ObjCInterfaces are just specialized ObjCObjects.
11904 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
11905 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
11906
11907 // Canonicalize ExtVector -> Vector.
11908 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
11909 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
11910
11911 // If the canonical type classes don't match.
11912 if (LHSClass != RHSClass) {
11913 // Note that we only have special rules for turning block enum
11914 // returns into block int returns, not vice-versa.
11915 if (const auto *ETy = LHS->getAsCanonical<EnumType>()) {
11916 return mergeEnumWithInteger(*this, ETy, RHS, false);
11917 }
11918 if (const EnumType *ETy = RHS->getAsCanonical<EnumType>()) {
11919 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
11920 }
11921 // allow block pointer type to match an 'id' type.
11922 if (OfBlockPointer && !BlockReturnType) {
11923 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
11924 return LHS;
11925 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
11926 return RHS;
11927 }
11928 // Allow __auto_type to match anything; it merges to the type with more
11929 // information.
11930 if (const auto *AT = LHS->getAs<AutoType>()) {
11931 if (!AT->isDeduced() && AT->isGNUAutoType())
11932 return RHS;
11933 }
11934 if (const auto *AT = RHS->getAs<AutoType>()) {
11935 if (!AT->isDeduced() && AT->isGNUAutoType())
11936 return LHS;
11937 }
11938 return {};
11939 }
11940
11941 // The canonical type classes match.
11942 switch (LHSClass) {
11943#define TYPE(Class, Base)
11944#define ABSTRACT_TYPE(Class, Base)
11945#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
11946#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
11947#define DEPENDENT_TYPE(Class, Base) case Type::Class:
11948#include "clang/AST/TypeNodes.inc"
11949 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
11950
11951 case Type::Auto:
11952 case Type::DeducedTemplateSpecialization:
11953 case Type::LValueReference:
11954 case Type::RValueReference:
11955 case Type::MemberPointer:
11956 llvm_unreachable("C++ should never be in mergeTypes");
11957
11958 case Type::ObjCInterface:
11959 case Type::IncompleteArray:
11960 case Type::VariableArray:
11961 case Type::FunctionProto:
11962 case Type::ExtVector:
11963 case Type::OverflowBehavior:
11964 llvm_unreachable("Types are eliminated above");
11965
11966 case Type::Pointer:
11967 {
11968 // Merge two pointer types, while trying to preserve typedef info
11969 QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType();
11970 QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType();
11971 if (Unqualified) {
11972 LHSPointee = LHSPointee.getUnqualifiedType();
11973 RHSPointee = RHSPointee.getUnqualifiedType();
11974 }
11975 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
11976 Unqualified);
11977 if (ResultType.isNull())
11978 return {};
11979 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
11980 return LHS;
11981 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
11982 return RHS;
11983 return getPointerType(ResultType);
11984 }
11985 case Type::BlockPointer:
11986 {
11987 // Merge two block pointer types, while trying to preserve typedef info
11988 QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType();
11989 QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType();
11990 if (Unqualified) {
11991 LHSPointee = LHSPointee.getUnqualifiedType();
11992 RHSPointee = RHSPointee.getUnqualifiedType();
11993 }
11994 if (getLangOpts().OpenCL) {
11995 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
11996 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
11997 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
11998 // 6.12.5) thus the following check is asymmetric.
11999 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual, *this))
12000 return {};
12001 LHSPteeQual.removeAddressSpace();
12002 RHSPteeQual.removeAddressSpace();
12003 LHSPointee =
12004 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
12005 RHSPointee =
12006 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
12007 }
12008 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
12009 Unqualified);
12010 if (ResultType.isNull())
12011 return {};
12012 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
12013 return LHS;
12014 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
12015 return RHS;
12016 return getBlockPointerType(ResultType);
12017 }
12018 case Type::Atomic:
12019 {
12020 // Merge two pointer types, while trying to preserve typedef info
12021 QualType LHSValue = LHS->castAs<AtomicType>()->getValueType();
12022 QualType RHSValue = RHS->castAs<AtomicType>()->getValueType();
12023 if (Unqualified) {
12024 LHSValue = LHSValue.getUnqualifiedType();
12025 RHSValue = RHSValue.getUnqualifiedType();
12026 }
12027 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
12028 Unqualified);
12029 if (ResultType.isNull())
12030 return {};
12031 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
12032 return LHS;
12033 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
12034 return RHS;
12035 return getAtomicType(ResultType);
12036 }
12037 case Type::ConstantArray:
12038 {
12039 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
12040 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
12041 if (LCAT && RCAT && RCAT->getZExtSize() != LCAT->getZExtSize())
12042 return {};
12043
12044 QualType LHSElem = getAsArrayType(LHS)->getElementType();
12045 QualType RHSElem = getAsArrayType(RHS)->getElementType();
12046 if (Unqualified) {
12047 LHSElem = LHSElem.getUnqualifiedType();
12048 RHSElem = RHSElem.getUnqualifiedType();
12049 }
12050
12051 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
12052 if (ResultType.isNull())
12053 return {};
12054
12055 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
12056 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
12057
12058 // If either side is a variable array, and both are complete, check whether
12059 // the current dimension is definite.
12060 if (LVAT || RVAT) {
12061 auto SizeFetch = [this](const VariableArrayType* VAT,
12062 const ConstantArrayType* CAT)
12063 -> std::pair<bool,llvm::APInt> {
12064 if (VAT) {
12065 std::optional<llvm::APSInt> TheInt;
12066 Expr *E = VAT->getSizeExpr();
12067 if (E && (TheInt = E->getIntegerConstantExpr(*this)))
12068 return std::make_pair(true, *TheInt);
12069 return std::make_pair(false, llvm::APSInt());
12070 }
12071 if (CAT)
12072 return std::make_pair(true, CAT->getSize());
12073 return std::make_pair(false, llvm::APInt());
12074 };
12075
12076 bool HaveLSize, HaveRSize;
12077 llvm::APInt LSize, RSize;
12078 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
12079 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
12080 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
12081 return {}; // Definite, but unequal, array dimension
12082 }
12083
12084 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
12085 return LHS;
12086 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
12087 return RHS;
12088 if (LCAT)
12089 return getConstantArrayType(ResultType, LCAT->getSize(),
12090 LCAT->getSizeExpr(), ArraySizeModifier(), 0);
12091 if (RCAT)
12092 return getConstantArrayType(ResultType, RCAT->getSize(),
12093 RCAT->getSizeExpr(), ArraySizeModifier(), 0);
12094 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
12095 return LHS;
12096 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
12097 return RHS;
12098 if (LVAT) {
12099 // FIXME: This isn't correct! But tricky to implement because
12100 // the array's size has to be the size of LHS, but the type
12101 // has to be different.
12102 return LHS;
12103 }
12104 if (RVAT) {
12105 // FIXME: This isn't correct! But tricky to implement because
12106 // the array's size has to be the size of RHS, but the type
12107 // has to be different.
12108 return RHS;
12109 }
12110 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
12111 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
12112 return getIncompleteArrayType(ResultType, ArraySizeModifier(), 0);
12113 }
12114 case Type::FunctionNoProto:
12115 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified,
12116 /*AllowCXX=*/false, IsConditionalOperator);
12117 case Type::Record:
12118 case Type::Enum:
12119 return mergeTagDefinitions(LHS, RHS);
12120 case Type::Builtin:
12121 // Only exactly equal builtin types are compatible, which is tested above.
12122 return {};
12123 case Type::Complex:
12124 // Distinct complex types are incompatible.
12125 return {};
12126 case Type::Vector:
12127 // FIXME: The merged type should be an ExtVector!
12128 if (areCompatVectorTypes(LHSCan->castAs<VectorType>(),
12129 RHSCan->castAs<VectorType>()))
12130 return LHS;
12131 return {};
12132 case Type::ConstantMatrix:
12134 RHSCan->castAs<ConstantMatrixType>()))
12135 return LHS;
12136 return {};
12137 case Type::ObjCObject: {
12138 // Check if the types are assignment compatible.
12139 // FIXME: This should be type compatibility, e.g. whether
12140 // "LHS x; RHS x;" at global scope is legal.
12142 RHS->castAs<ObjCObjectType>()))
12143 return LHS;
12144 return {};
12145 }
12146 case Type::ObjCObjectPointer:
12147 if (OfBlockPointer) {
12150 RHS->castAs<ObjCObjectPointerType>(), BlockReturnType))
12151 return LHS;
12152 return {};
12153 }
12156 return LHS;
12157 return {};
12158 case Type::Pipe:
12159 assert(LHS != RHS &&
12160 "Equivalent pipe types should have already been handled!");
12161 return {};
12162 case Type::ArrayParameter:
12163 assert(LHS != RHS &&
12164 "Equivalent ArrayParameter types should have already been handled!");
12165 return {};
12166 case Type::BitInt: {
12167 // Merge two bit-precise int types, while trying to preserve typedef info.
12168 bool LHSUnsigned = LHS->castAs<BitIntType>()->isUnsigned();
12169 bool RHSUnsigned = RHS->castAs<BitIntType>()->isUnsigned();
12170 unsigned LHSBits = LHS->castAs<BitIntType>()->getNumBits();
12171 unsigned RHSBits = RHS->castAs<BitIntType>()->getNumBits();
12172
12173 // Like unsigned/int, shouldn't have a type if they don't match.
12174 if (LHSUnsigned != RHSUnsigned)
12175 return {};
12176
12177 if (LHSBits != RHSBits)
12178 return {};
12179 return LHS;
12180 }
12181 case Type::HLSLAttributedResource: {
12182 const HLSLAttributedResourceType *LHSTy =
12183 LHS->castAs<HLSLAttributedResourceType>();
12184 const HLSLAttributedResourceType *RHSTy =
12185 RHS->castAs<HLSLAttributedResourceType>();
12186 assert(LHSTy->getWrappedType() == RHSTy->getWrappedType() &&
12187 LHSTy->getWrappedType()->isHLSLResourceType() &&
12188 "HLSLAttributedResourceType should always wrap __hlsl_resource_t");
12189
12190 if (LHSTy->getAttrs() == RHSTy->getAttrs() &&
12191 LHSTy->getContainedType() == RHSTy->getContainedType())
12192 return LHS;
12193 return {};
12194 }
12195 case Type::HLSLInlineSpirv:
12196 const HLSLInlineSpirvType *LHSTy = LHS->castAs<HLSLInlineSpirvType>();
12197 const HLSLInlineSpirvType *RHSTy = RHS->castAs<HLSLInlineSpirvType>();
12198
12199 if (LHSTy->getOpcode() == RHSTy->getOpcode() &&
12200 LHSTy->getSize() == RHSTy->getSize() &&
12201 LHSTy->getAlignment() == RHSTy->getAlignment()) {
12202 for (size_t I = 0; I < LHSTy->getOperands().size(); I++)
12203 if (LHSTy->getOperands()[I] != RHSTy->getOperands()[I])
12204 return {};
12205
12206 return LHS;
12207 }
12208 return {};
12209 }
12210
12211 llvm_unreachable("Invalid Type::Class!");
12212}
12213
12215 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
12216 bool &CanUseFirst, bool &CanUseSecond,
12218 assert(NewParamInfos.empty() && "param info list not empty");
12219 CanUseFirst = CanUseSecond = true;
12220 bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
12221 bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
12222
12223 // Fast path: if the first type doesn't have ext parameter infos,
12224 // we match if and only if the second type also doesn't have them.
12225 if (!FirstHasInfo && !SecondHasInfo)
12226 return true;
12227
12228 bool NeedParamInfo = false;
12229 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
12230 : SecondFnType->getExtParameterInfos().size();
12231
12232 for (size_t I = 0; I < E; ++I) {
12233 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
12234 if (FirstHasInfo)
12235 FirstParam = FirstFnType->getExtParameterInfo(I);
12236 if (SecondHasInfo)
12237 SecondParam = SecondFnType->getExtParameterInfo(I);
12238
12239 // Cannot merge unless everything except the noescape flag matches.
12240 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
12241 return false;
12242
12243 bool FirstNoEscape = FirstParam.isNoEscape();
12244 bool SecondNoEscape = SecondParam.isNoEscape();
12245 bool IsNoEscape = FirstNoEscape && SecondNoEscape;
12246 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
12247 if (NewParamInfos.back().getOpaqueValue())
12248 NeedParamInfo = true;
12249 if (FirstNoEscape != IsNoEscape)
12250 CanUseFirst = false;
12251 if (SecondNoEscape != IsNoEscape)
12252 CanUseSecond = false;
12253 }
12254
12255 if (!NeedParamInfo)
12256 NewParamInfos.clear();
12257
12258 return true;
12259}
12260
12262 if (auto It = ObjCLayouts.find(D); It != ObjCLayouts.end()) {
12263 It->second = nullptr;
12264 for (auto *SubClass : ObjCSubClasses.lookup(D))
12265 ResetObjCLayout(SubClass);
12266 }
12267}
12268
12269/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
12270/// 'RHS' attributes and returns the merged version; including for function
12271/// return types.
12273 QualType LHSCan = getCanonicalType(LHS),
12274 RHSCan = getCanonicalType(RHS);
12275 // If two types are identical, they are compatible.
12276 if (LHSCan == RHSCan)
12277 return LHS;
12278 if (RHSCan->isFunctionType()) {
12279 if (!LHSCan->isFunctionType())
12280 return {};
12281 QualType OldReturnType =
12282 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
12283 QualType NewReturnType =
12284 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
12285 QualType ResReturnType =
12286 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
12287 if (ResReturnType.isNull())
12288 return {};
12289 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
12290 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
12291 // In either case, use OldReturnType to build the new function type.
12292 const auto *F = LHS->castAs<FunctionType>();
12293 if (const auto *FPT = cast<FunctionProtoType>(F)) {
12294 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12295 EPI.ExtInfo = getFunctionExtInfo(LHS);
12296 QualType ResultType =
12297 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
12298 return ResultType;
12299 }
12300 }
12301 return {};
12302 }
12303
12304 // If the qualifiers are different, the types can still be merged.
12305 Qualifiers LQuals = LHSCan.getLocalQualifiers();
12306 Qualifiers RQuals = RHSCan.getLocalQualifiers();
12307 if (LQuals != RQuals) {
12308 // If any of these qualifiers are different, we have a type mismatch.
12309 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
12310 LQuals.getAddressSpace() != RQuals.getAddressSpace())
12311 return {};
12312
12313 // Exactly one GC qualifier difference is allowed: __strong is
12314 // okay if the other type has no GC qualifier but is an Objective
12315 // C object pointer (i.e. implicitly strong by default). We fix
12316 // this by pretending that the unqualified type was actually
12317 // qualified __strong.
12318 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
12319 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
12320 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
12321
12322 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
12323 return {};
12324
12325 if (GC_L == Qualifiers::Strong)
12326 return LHS;
12327 if (GC_R == Qualifiers::Strong)
12328 return RHS;
12329 return {};
12330 }
12331
12332 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
12333 QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType();
12334 QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType();
12335 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
12336 if (ResQT == LHSBaseQT)
12337 return LHS;
12338 if (ResQT == RHSBaseQT)
12339 return RHS;
12340 }
12341 return {};
12342}
12343
12344//===----------------------------------------------------------------------===//
12345// Integer Predicates
12346//===----------------------------------------------------------------------===//
12347
12349 if (const auto *ED = T->getAsEnumDecl())
12350 T = ED->getIntegerType();
12351 if (T->isBooleanType())
12352 return 1;
12353 if (const auto *EIT = T->getAs<BitIntType>())
12354 return EIT->getNumBits();
12355 // For builtin types, just use the standard type sizing method
12356 return (unsigned)getTypeSize(T);
12357}
12358
12360 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
12361 T->isFixedPointType()) &&
12362 "Unexpected type");
12363
12364 // Turn <4 x signed int> -> <4 x unsigned int>
12365 if (const auto *VTy = T->getAs<VectorType>())
12366 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
12367 VTy->getNumElements(), VTy->getVectorKind());
12368
12369 // For _BitInt, return an unsigned _BitInt with same width.
12370 if (const auto *EITy = T->getAs<BitIntType>())
12371 return getBitIntType(/*Unsigned=*/true, EITy->getNumBits());
12372
12373 // For the overflow behavior types, construct a new unsigned variant
12374 if (const auto *OBT = T->getAs<OverflowBehaviorType>())
12376 OBT->getBehaviorKind(),
12377 getCorrespondingUnsignedType(OBT->getUnderlyingType()));
12378
12379 // For enums, get the underlying integer type of the enum, and let the general
12380 // integer type signchanging code handle it.
12381 if (const auto *ED = T->getAsEnumDecl())
12382 T = ED->getIntegerType();
12383
12384 switch (T->castAs<BuiltinType>()->getKind()) {
12385 case BuiltinType::Char_U:
12386 // Plain `char` is mapped to `unsigned char` even if it's already unsigned
12387 case BuiltinType::Char_S:
12388 case BuiltinType::SChar:
12389 case BuiltinType::Char8:
12390 return UnsignedCharTy;
12391 case BuiltinType::Short:
12392 return UnsignedShortTy;
12393 case BuiltinType::Int:
12394 return UnsignedIntTy;
12395 case BuiltinType::Long:
12396 return UnsignedLongTy;
12397 case BuiltinType::LongLong:
12398 return UnsignedLongLongTy;
12399 case BuiltinType::Int128:
12400 return UnsignedInt128Ty;
12401 // wchar_t is special. It is either signed or not, but when it's signed,
12402 // there's no matching "unsigned wchar_t". Therefore we return the unsigned
12403 // version of its underlying type instead.
12404 case BuiltinType::WChar_S:
12405 return getUnsignedWCharType();
12406
12407 case BuiltinType::ShortAccum:
12408 return UnsignedShortAccumTy;
12409 case BuiltinType::Accum:
12410 return UnsignedAccumTy;
12411 case BuiltinType::LongAccum:
12412 return UnsignedLongAccumTy;
12413 case BuiltinType::SatShortAccum:
12415 case BuiltinType::SatAccum:
12416 return SatUnsignedAccumTy;
12417 case BuiltinType::SatLongAccum:
12419 case BuiltinType::ShortFract:
12420 return UnsignedShortFractTy;
12421 case BuiltinType::Fract:
12422 return UnsignedFractTy;
12423 case BuiltinType::LongFract:
12424 return UnsignedLongFractTy;
12425 case BuiltinType::SatShortFract:
12427 case BuiltinType::SatFract:
12428 return SatUnsignedFractTy;
12429 case BuiltinType::SatLongFract:
12431 default:
12432 assert((T->hasUnsignedIntegerRepresentation() ||
12433 T->isUnsignedFixedPointType()) &&
12434 "Unexpected signed integer or fixed point type");
12435 return T;
12436 }
12437}
12438
12440 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
12441 T->isFixedPointType()) &&
12442 "Unexpected type");
12443
12444 // Turn <4 x unsigned int> -> <4 x signed int>
12445 if (const auto *VTy = T->getAs<VectorType>())
12446 return getVectorType(getCorrespondingSignedType(VTy->getElementType()),
12447 VTy->getNumElements(), VTy->getVectorKind());
12448
12449 // For _BitInt, return a signed _BitInt with same width.
12450 if (const auto *EITy = T->getAs<BitIntType>())
12451 return getBitIntType(/*Unsigned=*/false, EITy->getNumBits());
12452
12453 // For enums, get the underlying integer type of the enum, and let the general
12454 // integer type signchanging code handle it.
12455 if (const auto *ED = T->getAsEnumDecl())
12456 T = ED->getIntegerType();
12457
12458 switch (T->castAs<BuiltinType>()->getKind()) {
12459 case BuiltinType::Char_S:
12460 // Plain `char` is mapped to `signed char` even if it's already signed
12461 case BuiltinType::Char_U:
12462 case BuiltinType::UChar:
12463 case BuiltinType::Char8:
12464 return SignedCharTy;
12465 case BuiltinType::UShort:
12466 return ShortTy;
12467 case BuiltinType::UInt:
12468 return IntTy;
12469 case BuiltinType::ULong:
12470 return LongTy;
12471 case BuiltinType::ULongLong:
12472 return LongLongTy;
12473 case BuiltinType::UInt128:
12474 return Int128Ty;
12475 // wchar_t is special. It is either unsigned or not, but when it's unsigned,
12476 // there's no matching "signed wchar_t". Therefore we return the signed
12477 // version of its underlying type instead.
12478 case BuiltinType::WChar_U:
12479 return getSignedWCharType();
12480
12481 case BuiltinType::UShortAccum:
12482 return ShortAccumTy;
12483 case BuiltinType::UAccum:
12484 return AccumTy;
12485 case BuiltinType::ULongAccum:
12486 return LongAccumTy;
12487 case BuiltinType::SatUShortAccum:
12488 return SatShortAccumTy;
12489 case BuiltinType::SatUAccum:
12490 return SatAccumTy;
12491 case BuiltinType::SatULongAccum:
12492 return SatLongAccumTy;
12493 case BuiltinType::UShortFract:
12494 return ShortFractTy;
12495 case BuiltinType::UFract:
12496 return FractTy;
12497 case BuiltinType::ULongFract:
12498 return LongFractTy;
12499 case BuiltinType::SatUShortFract:
12500 return SatShortFractTy;
12501 case BuiltinType::SatUFract:
12502 return SatFractTy;
12503 case BuiltinType::SatULongFract:
12504 return SatLongFractTy;
12505 default:
12506 assert(
12507 (T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) &&
12508 "Unexpected signed integer or fixed point type");
12509 return T;
12510 }
12511}
12512
12514
12517
12518//===----------------------------------------------------------------------===//
12519// Builtin Type Computation
12520//===----------------------------------------------------------------------===//
12521
12522/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
12523/// pointer over the consumed characters. This returns the resultant type. If
12524/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
12525/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
12526/// a vector of "i*".
12527///
12528/// RequiresICE is filled in on return to indicate whether the value is required
12529/// to be an Integer Constant Expression.
12530static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
12532 bool &RequiresICE,
12533 bool AllowTypeModifiers) {
12534 // Modifiers.
12535 int HowLong = 0;
12536 bool Signed = false, Unsigned = false;
12537 RequiresICE = false;
12538
12539 // Read the prefixed modifiers first.
12540 bool Done = false;
12541 #ifndef NDEBUG
12542 bool IsSpecial = false;
12543 #endif
12544 while (!Done) {
12545 switch (*Str++) {
12546 default: Done = true; --Str; break;
12547 case 'I':
12548 RequiresICE = true;
12549 break;
12550 case 'S':
12551 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
12552 assert(!Signed && "Can't use 'S' modifier multiple times!");
12553 Signed = true;
12554 break;
12555 case 'U':
12556 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
12557 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
12558 Unsigned = true;
12559 break;
12560 case 'L':
12561 assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers");
12562 assert(HowLong <= 2 && "Can't have LLLL modifier");
12563 ++HowLong;
12564 break;
12565 case 'N':
12566 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
12567 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12568 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
12569 #ifndef NDEBUG
12570 IsSpecial = true;
12571 #endif
12572 if (Context.getTargetInfo().getLongWidth() == 32)
12573 ++HowLong;
12574 break;
12575 case 'W':
12576 // This modifier represents int64 type.
12577 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12578 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
12579 #ifndef NDEBUG
12580 IsSpecial = true;
12581 #endif
12582 switch (Context.getTargetInfo().getInt64Type()) {
12583 default:
12584 llvm_unreachable("Unexpected integer type");
12586 HowLong = 1;
12587 break;
12589 HowLong = 2;
12590 break;
12591 }
12592 break;
12593 case 'Z':
12594 // This modifier represents int32 type.
12595 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12596 assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
12597 #ifndef NDEBUG
12598 IsSpecial = true;
12599 #endif
12600 switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) {
12601 default:
12602 llvm_unreachable("Unexpected integer type");
12604 HowLong = 0;
12605 break;
12607 HowLong = 1;
12608 break;
12610 HowLong = 2;
12611 break;
12612 }
12613 break;
12614 case 'O':
12615 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12616 assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
12617 #ifndef NDEBUG
12618 IsSpecial = true;
12619 #endif
12620 if (Context.getLangOpts().OpenCL)
12621 HowLong = 1;
12622 else
12623 HowLong = 2;
12624 break;
12625 }
12626 }
12627
12628 QualType Type;
12629
12630 // Read the base type.
12631 switch (*Str++) {
12632 default:
12633 llvm_unreachable("Unknown builtin type letter!");
12634 case 'x':
12635 assert(HowLong == 0 && !Signed && !Unsigned &&
12636 "Bad modifiers used with 'x'!");
12637 Type = Context.Float16Ty;
12638 break;
12639 case 'y':
12640 assert(HowLong == 0 && !Signed && !Unsigned &&
12641 "Bad modifiers used with 'y'!");
12642 Type = Context.BFloat16Ty;
12643 break;
12644 case 'v':
12645 assert(HowLong == 0 && !Signed && !Unsigned &&
12646 "Bad modifiers used with 'v'!");
12647 Type = Context.VoidTy;
12648 break;
12649 case 'h':
12650 assert(HowLong == 0 && !Signed && !Unsigned &&
12651 "Bad modifiers used with 'h'!");
12652 Type = Context.HalfTy;
12653 break;
12654 case 'f':
12655 assert(HowLong == 0 && !Signed && !Unsigned &&
12656 "Bad modifiers used with 'f'!");
12657 Type = Context.FloatTy;
12658 break;
12659 case 'd':
12660 assert(HowLong < 3 && !Signed && !Unsigned &&
12661 "Bad modifiers used with 'd'!");
12662 if (HowLong == 1)
12663 Type = Context.LongDoubleTy;
12664 else if (HowLong == 2)
12665 Type = Context.Float128Ty;
12666 else
12667 Type = Context.DoubleTy;
12668 break;
12669 case 's':
12670 assert(HowLong == 0 && "Bad modifiers used with 's'!");
12671 if (Unsigned)
12672 Type = Context.UnsignedShortTy;
12673 else
12674 Type = Context.ShortTy;
12675 break;
12676 case 'i':
12677 if (HowLong == 3)
12678 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
12679 else if (HowLong == 2)
12680 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
12681 else if (HowLong == 1)
12682 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
12683 else
12684 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
12685 break;
12686 case 'c':
12687 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
12688 if (Signed)
12689 Type = Context.SignedCharTy;
12690 else if (Unsigned)
12691 Type = Context.UnsignedCharTy;
12692 else
12693 Type = Context.CharTy;
12694 break;
12695 case 'b': // boolean
12696 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
12697 Type = Context.BoolTy;
12698 break;
12699 case 'z': // size_t.
12700 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
12701 Type = Context.getSizeType();
12702 break;
12703 case 'w': // wchar_t.
12704 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
12705 Type = Context.getWideCharType();
12706 break;
12707 case 'F':
12708 Type = Context.getCFConstantStringType();
12709 break;
12710 case 'G':
12711 Type = Context.getObjCIdType();
12712 break;
12713 case 'H':
12714 Type = Context.getObjCSelType();
12715 break;
12716 case 'M':
12717 Type = Context.getObjCSuperType();
12718 break;
12719 case 'a':
12720 Type = Context.getBuiltinVaListType();
12721 assert(!Type.isNull() && "builtin va list type not initialized!");
12722 break;
12723 case 'A':
12724 // This is a "reference" to a va_list; however, what exactly
12725 // this means depends on how va_list is defined. There are two
12726 // different kinds of va_list: ones passed by value, and ones
12727 // passed by reference. An example of a by-value va_list is
12728 // x86, where va_list is a char*. An example of by-ref va_list
12729 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
12730 // we want this argument to be a char*&; for x86-64, we want
12731 // it to be a __va_list_tag*.
12732 Type = Context.getBuiltinVaListType();
12733 assert(!Type.isNull() && "builtin va list type not initialized!");
12734 if (Type->isArrayType())
12735 Type = Context.getArrayDecayedType(Type);
12736 else
12737 Type = Context.getLValueReferenceType(Type);
12738 break;
12739 case 'q': {
12740 char *End;
12741 unsigned NumElements = strtoul(Str, &End, 10);
12742 assert(End != Str && "Missing vector size");
12743 Str = End;
12744
12745 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12746 RequiresICE, false);
12747 assert(!RequiresICE && "Can't require vector ICE");
12748
12749 Type = Context.getScalableVectorType(ElementType, NumElements);
12750 break;
12751 }
12752 case 'Q': {
12753 switch (*Str++) {
12754 case 'a': {
12755 Type = Context.SveCountTy;
12756 break;
12757 }
12758 case 'b': {
12759 Type = Context.AMDGPUBufferRsrcTy;
12760 break;
12761 }
12762 case 'c': {
12763 Type = Context.AMDGPUFeaturePredicateTy;
12764 break;
12765 }
12766 case 't': {
12767 Type = Context.AMDGPUTextureTy;
12768 break;
12769 }
12770 case 'r': {
12771 Type = Context.HLSLResourceTy;
12772 break;
12773 }
12774 default:
12775 llvm_unreachable("Unexpected target builtin type");
12776 }
12777 break;
12778 }
12779 case 'V': {
12780 char *End;
12781 unsigned NumElements = strtoul(Str, &End, 10);
12782 assert(End != Str && "Missing vector size");
12783 Str = End;
12784
12785 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12786 RequiresICE, false);
12787 assert(!RequiresICE && "Can't require vector ICE");
12788
12789 // TODO: No way to make AltiVec vectors in builtins yet.
12790 Type = Context.getVectorType(ElementType, NumElements, VectorKind::Generic);
12791 break;
12792 }
12793 case 'E': {
12794 char *End;
12795
12796 unsigned NumElements = strtoul(Str, &End, 10);
12797 assert(End != Str && "Missing vector size");
12798
12799 Str = End;
12800
12801 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12802 false);
12803 Type = Context.getExtVectorType(ElementType, NumElements);
12804 break;
12805 }
12806 case 'X': {
12807 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12808 false);
12809 assert(!RequiresICE && "Can't require complex ICE");
12810 Type = Context.getComplexType(ElementType);
12811 break;
12812 }
12813 case 'Y':
12814 Type = Context.getPointerDiffType();
12815 break;
12816 case 'P':
12817 Type = Context.getFILEType();
12818 if (Type.isNull()) {
12820 return {};
12821 }
12822 break;
12823 case 'J':
12824 if (Signed)
12825 Type = Context.getsigjmp_bufType();
12826 else
12827 Type = Context.getjmp_bufType();
12828
12829 if (Type.isNull()) {
12831 return {};
12832 }
12833 break;
12834 case 'K':
12835 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
12836 Type = Context.getucontext_tType();
12837
12838 if (Type.isNull()) {
12840 return {};
12841 }
12842 break;
12843 case 'p':
12844 Type = Context.getProcessIDType();
12845 break;
12846 case 'm':
12847 Type = Context.MFloat8Ty;
12848 break;
12849 }
12850
12851 // If there are modifiers and if we're allowed to parse them, go for it.
12852 Done = !AllowTypeModifiers;
12853 while (!Done) {
12854 switch (char c = *Str++) {
12855 default: Done = true; --Str; break;
12856 case '*':
12857 case '&': {
12858 // Both pointers and references can have their pointee types
12859 // qualified with an address space.
12860 char *End;
12861 unsigned AddrSpace = strtoul(Str, &End, 10);
12862 if (End != Str) {
12863 // Note AddrSpace == 0 is not the same as an unspecified address space.
12864 Type = Context.getAddrSpaceQualType(
12865 Type,
12866 Context.getLangASForBuiltinAddressSpace(AddrSpace));
12867 Str = End;
12868 }
12869 if (c == '*')
12870 Type = Context.getPointerType(Type);
12871 else
12872 Type = Context.getLValueReferenceType(Type);
12873 break;
12874 }
12875 // FIXME: There's no way to have a built-in with an rvalue ref arg.
12876 case 'C':
12877 Type = Type.withConst();
12878 break;
12879 case 'D':
12880 Type = Context.getVolatileType(Type);
12881 break;
12882 case 'R':
12883 Type = Type.withRestrict();
12884 break;
12885 }
12886 }
12887
12888 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
12889 "Integer constant 'I' type must be an integer");
12890
12891 return Type;
12892}
12893
12894// On some targets such as PowerPC, some of the builtins are defined with custom
12895// type descriptors for target-dependent types. These descriptors are decoded in
12896// other functions, but it may be useful to be able to fall back to default
12897// descriptor decoding to define builtins mixing target-dependent and target-
12898// independent types. This function allows decoding one type descriptor with
12899// default decoding.
12900QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context,
12901 GetBuiltinTypeError &Error, bool &RequireICE,
12902 bool AllowTypeModifiers) const {
12903 return DecodeTypeFromStr(Str, Context, Error, RequireICE, AllowTypeModifiers);
12904}
12905
12906/// GetBuiltinType - Return the type for the specified builtin.
12909 unsigned *IntegerConstantArgs) const {
12910 const char *TypeStr = BuiltinInfo.getTypeString(Id);
12911 if (TypeStr[0] == '\0') {
12913 return {};
12914 }
12915
12916 SmallVector<QualType, 8> ArgTypes;
12917
12918 bool RequiresICE = false;
12919 Error = GE_None;
12920 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
12921 RequiresICE, true);
12922 if (Error != GE_None)
12923 return {};
12924
12925 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
12926
12927 while (TypeStr[0] && TypeStr[0] != '.') {
12928 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
12929 if (Error != GE_None)
12930 return {};
12931
12932 // If this argument is required to be an IntegerConstantExpression and the
12933 // caller cares, fill in the bitmask we return.
12934 if (RequiresICE && IntegerConstantArgs)
12935 *IntegerConstantArgs |= 1 << ArgTypes.size();
12936
12937 // Do array -> pointer decay. The builtin should use the decayed type.
12938 if (Ty->isArrayType())
12939 Ty = getArrayDecayedType(Ty);
12940
12941 ArgTypes.push_back(Ty);
12942 }
12943
12944 if (Id == Builtin::BI__GetExceptionInfo)
12945 return {};
12946
12947 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
12948 "'.' should only occur at end of builtin type list!");
12949
12950 bool Variadic = (TypeStr[0] == '.');
12951
12952 FunctionType::ExtInfo EI(Target->getDefaultCallingConv());
12953 if (BuiltinInfo.isNoReturn(Id))
12954 EI = EI.withNoReturn(true);
12955
12956 // We really shouldn't be making a no-proto type here.
12957 if (ArgTypes.empty() && Variadic && !getLangOpts().requiresStrictPrototypes())
12958 return getFunctionNoProtoType(ResType, EI);
12959
12961 EPI.ExtInfo = EI;
12962 EPI.Variadic = Variadic;
12963 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
12964 EPI.ExceptionSpec.Type =
12966
12967 return getFunctionType(ResType, ArgTypes, EPI);
12968}
12969
12971 const FunctionDecl *FD) {
12972 if (!FD->isExternallyVisible())
12973 return GVA_Internal;
12974
12975 // Non-user-provided functions get emitted as weak definitions with every
12976 // use, no matter whether they've been explicitly instantiated etc.
12977 if (!FD->isUserProvided())
12978 return GVA_DiscardableODR;
12979
12981 switch (FD->getTemplateSpecializationKind()) {
12982 case TSK_Undeclared:
12985 break;
12986
12988 return GVA_StrongODR;
12989
12990 // C++11 [temp.explicit]p10:
12991 // [ Note: The intent is that an inline function that is the subject of
12992 // an explicit instantiation declaration will still be implicitly
12993 // instantiated when used so that the body can be considered for
12994 // inlining, but that no out-of-line copy of the inline function would be
12995 // generated in the translation unit. -- end note ]
12998
13001 break;
13002 }
13003
13004 if (!FD->isInlined())
13005 return External;
13006
13007 if ((!Context.getLangOpts().CPlusPlus &&
13008 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13009 !FD->hasAttr<DLLExportAttr>()) ||
13010 FD->hasAttr<GNUInlineAttr>()) {
13011 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
13012
13013 // GNU or C99 inline semantics. Determine whether this symbol should be
13014 // externally visible.
13016 return External;
13017
13018 // C99 inline semantics, where the symbol is not externally visible.
13020 }
13021
13022 // Functions specified with extern and inline in -fms-compatibility mode
13023 // forcibly get emitted. While the body of the function cannot be later
13024 // replaced, the function definition cannot be discarded.
13025 if (FD->isMSExternInline())
13026 return GVA_StrongODR;
13027
13028 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13030 cast<CXXConstructorDecl>(FD)->isInheritingConstructor() &&
13031 !FD->hasAttr<DLLExportAttr>()) {
13032 // Both Clang and MSVC implement inherited constructors as forwarding
13033 // thunks that delegate to the base constructor. Keep non-dllexport
13034 // inheriting constructor thunks internal since they are not needed
13035 // outside the translation unit.
13036 //
13037 // dllexport inherited constructors are exempted so they are externally
13038 // visible, matching MSVC's export behavior. Inherited constructors
13039 // whose parameters prevent ABI-compatible forwarding (e.g. callee-
13040 // cleanup types) are excluded from export in Sema to avoid silent
13041 // runtime mismatches.
13042 return GVA_Internal;
13043 }
13044
13045 return GVA_DiscardableODR;
13046}
13047
13049 const Decl *D, GVALinkage L) {
13050 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
13051 // dllexport/dllimport on inline functions.
13052 if (D->hasAttr<DLLImportAttr>()) {
13053 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
13055 } else if (D->hasAttr<DLLExportAttr>()) {
13056 if (L == GVA_DiscardableODR)
13057 return GVA_StrongODR;
13058 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) {
13059 // Device-side functions with __global__ attribute must always be
13060 // visible externally so they can be launched from host.
13061 if (D->hasAttr<CUDAGlobalAttr>() &&
13062 (L == GVA_DiscardableODR || L == GVA_Internal))
13063 return GVA_StrongODR;
13064 // Single source offloading languages like CUDA/HIP need to be able to
13065 // access static device variables from host code of the same compilation
13066 // unit. This is done by externalizing the static variable with a shared
13067 // name between the host and device compilation which is the same for the
13068 // same compilation unit whereas different among different compilation
13069 // units.
13070 if (Context.shouldExternalize(D))
13071 return GVA_StrongExternal;
13072 }
13073 return L;
13074}
13075
13076/// Adjust the GVALinkage for a declaration based on what an external AST source
13077/// knows about whether there can be other definitions of this declaration.
13078static GVALinkage
13080 GVALinkage L) {
13081 ExternalASTSource *Source = Ctx.getExternalSource();
13082 if (!Source)
13083 return L;
13084
13085 switch (Source->hasExternalDefinitions(D)) {
13087 // Other translation units rely on us to provide the definition.
13088 if (L == GVA_DiscardableODR)
13089 return GVA_StrongODR;
13090 break;
13091
13094
13096 break;
13097 }
13098 return L;
13099}
13100
13106
13108 const VarDecl *VD) {
13109 // As an extension for interactive REPLs, make sure constant variables are
13110 // only emitted once instead of LinkageComputer::getLVForNamespaceScopeDecl
13111 // marking them as internal.
13112 if (Context.getLangOpts().CPlusPlus &&
13113 Context.getLangOpts().IncrementalExtensions &&
13114 VD->getType().isConstQualified() &&
13115 !VD->getType().isVolatileQualified() && !VD->isInline() &&
13117 return GVA_DiscardableODR;
13118
13119 if (!VD->isExternallyVisible())
13120 return GVA_Internal;
13121
13122 if (VD->isStaticLocal()) {
13123 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
13124 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
13125 LexicalContext = LexicalContext->getLexicalParent();
13126
13127 // ObjC Blocks can create local variables that don't have a FunctionDecl
13128 // LexicalContext.
13129 if (!LexicalContext)
13130 return GVA_DiscardableODR;
13131
13132 // Otherwise, let the static local variable inherit its linkage from the
13133 // nearest enclosing function.
13134 auto StaticLocalLinkage =
13135 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
13136
13137 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
13138 // be emitted in any object with references to the symbol for the object it
13139 // contains, whether inline or out-of-line."
13140 // Similar behavior is observed with MSVC. An alternative ABI could use
13141 // StrongODR/AvailableExternally to match the function, but none are
13142 // known/supported currently.
13143 if (StaticLocalLinkage == GVA_StrongODR ||
13144 StaticLocalLinkage == GVA_AvailableExternally)
13145 return GVA_DiscardableODR;
13146 return StaticLocalLinkage;
13147 }
13148
13149 // MSVC treats in-class initialized static data members as definitions.
13150 // By giving them non-strong linkage, out-of-line definitions won't
13151 // cause link errors.
13152 if (Context.isMSStaticDataMemberInlineDefinition(VD))
13153 return GVA_DiscardableODR;
13154
13155 // Most non-template variables have strong linkage; inline variables are
13156 // linkonce_odr or (occasionally, for compatibility) weak_odr.
13157 GVALinkage StrongLinkage;
13158 switch (Context.getInlineVariableDefinitionKind(VD)) {
13160 StrongLinkage = GVA_StrongExternal;
13161 break;
13164 StrongLinkage = GVA_DiscardableODR;
13165 break;
13167 StrongLinkage = GVA_StrongODR;
13168 break;
13169 }
13170
13171 switch (VD->getTemplateSpecializationKind()) {
13172 case TSK_Undeclared:
13173 return StrongLinkage;
13174
13176 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13177 VD->isStaticDataMember()
13179 : StrongLinkage;
13180
13182 return GVA_StrongODR;
13183
13186
13188 return GVA_DiscardableODR;
13189 }
13190
13191 llvm_unreachable("Invalid Linkage!");
13192}
13193
13199
13201 if (const auto *VD = dyn_cast<VarDecl>(D)) {
13202 if (!VD->isFileVarDecl())
13203 return false;
13204 // Global named register variables (GNU extension) are never emitted.
13205 if (VD->getStorageClass() == SC_Register)
13206 return false;
13207 if (VD->getDescribedVarTemplate() ||
13209 return false;
13210 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
13211 // We never need to emit an uninstantiated function template.
13212 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
13213 return false;
13214 } else if (isa<PragmaCommentDecl>(D))
13215 return true;
13217 return true;
13218 else if (isa<OMPRequiresDecl>(D))
13219 return true;
13220 else if (isa<OMPThreadPrivateDecl>(D))
13221 return !D->getDeclContext()->isDependentContext();
13222 else if (isa<OMPAllocateDecl>(D))
13223 return !D->getDeclContext()->isDependentContext();
13225 return !D->getDeclContext()->isDependentContext();
13226 else if (isa<ImportDecl>(D))
13227 return true;
13228 else
13229 return false;
13230
13231 // If this is a member of a class template, we do not need to emit it.
13233 return false;
13234
13235 // Weak references don't produce any output by themselves.
13236 if (D->hasAttr<WeakRefAttr>())
13237 return false;
13238
13239 // SYCL device compilation requires that functions defined with the
13240 // sycl_kernel_entry_point or sycl_external attributes be emitted. All
13241 // other entities are emitted only if they are used by a function
13242 // defined with one of those attributes.
13243 if (LangOpts.SYCLIsDevice)
13244 return isa<FunctionDecl>(D) && (D->hasAttr<SYCLKernelEntryPointAttr>() ||
13245 D->hasAttr<SYCLExternalAttr>());
13246
13247 // Aliases and used decls are required.
13248 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
13249 return true;
13250
13251 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
13252 // Forward declarations aren't required.
13253 if (!FD->doesThisDeclarationHaveABody())
13254 return FD->doesDeclarationForceExternallyVisibleDefinition();
13255
13256 // Constructors and destructors are required.
13257 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
13258 return true;
13259
13260 // The key function for a class is required. This rule only comes
13261 // into play when inline functions can be key functions, though.
13262 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
13263 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
13264 const CXXRecordDecl *RD = MD->getParent();
13265 if (MD->isOutOfLine() && RD->isDynamicClass()) {
13266 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
13267 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
13268 return true;
13269 }
13270 }
13271 }
13272
13274
13275 // static, static inline, always_inline, and extern inline functions can
13276 // always be deferred. Normal inline functions can be deferred in C99/C++.
13277 // Implicit template instantiations can also be deferred in C++.
13279 }
13280
13281 const auto *VD = cast<VarDecl>(D);
13282 assert(VD->isFileVarDecl() && "Expected file scoped var");
13283
13284 // If the decl is marked as `declare target to`, it should be emitted for the
13285 // host and for the device.
13286 if (LangOpts.OpenMP &&
13287 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
13288 return true;
13289
13290 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
13292 return false;
13293
13294 if (VD->shouldEmitInExternalSource())
13295 return false;
13296
13297 // Variables that can be needed in other TUs are required.
13300 return true;
13301
13302 // We never need to emit a variable that is available in another TU.
13304 return false;
13305
13306 // Variables that have destruction with side-effects are required.
13307 if (VD->needsDestruction(*this))
13308 return true;
13309
13310 // Variables that have initialization with side-effects are required.
13311 if (VD->hasInitWithSideEffects())
13312 return true;
13313
13314 // Likewise, variables with tuple-like bindings are required if their
13315 // bindings have side-effects.
13316 if (const auto *DD = dyn_cast<DecompositionDecl>(VD)) {
13317 for (const auto *BD : DD->flat_bindings())
13318 if (const auto *BindingVD = BD->getHoldingVar())
13319 if (DeclMustBeEmitted(BindingVD))
13320 return true;
13321 }
13322
13323 return false;
13324}
13325
13327 const FunctionDecl *FD,
13328 llvm::function_ref<void(FunctionDecl *)> Pred) const {
13329 assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
13330 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
13331 FD = FD->getMostRecentDecl();
13332 // FIXME: The order of traversal here matters and depends on the order of
13333 // lookup results, which happens to be (mostly) oldest-to-newest, but we
13334 // shouldn't rely on that.
13335 for (auto *CurDecl :
13337 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
13338 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
13339 SeenDecls.insert(CurFD).second) {
13340 Pred(CurFD);
13341 }
13342 }
13343}
13344
13346 bool IsCXXMethod) const {
13347 // Pass through to the C++ ABI object
13348 if (IsCXXMethod)
13349 return ABI->getDefaultMethodCallConv(IsVariadic);
13350
13351 switch (LangOpts.getDefaultCallingConv()) {
13353 break;
13355 return CC_C;
13357 if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
13358 return CC_X86FastCall;
13359 break;
13361 if (!IsVariadic)
13362 return CC_X86StdCall;
13363 break;
13365 // __vectorcall cannot be applied to variadic functions.
13366 if (!IsVariadic)
13367 return CC_X86VectorCall;
13368 break;
13370 // __regcall cannot be applied to variadic functions.
13371 if (!IsVariadic)
13372 return CC_X86RegCall;
13373 break;
13375 if (!IsVariadic)
13376 return CC_M68kRTD;
13377 break;
13378 }
13379 return Target->getDefaultCallingConv();
13380}
13381
13383 // Pass through to the C++ ABI object
13384 return ABI->isNearlyEmpty(RD);
13385}
13386
13388 if (!VTContext) {
13389 auto ABI = Target->getCXXABI();
13390 if (ABI.isMicrosoft())
13391 VTContext.reset(new MicrosoftVTableContext(*this));
13392 else {
13393 VTContext.reset(new ItaniumVTableContext(*this));
13394 }
13395 }
13396 return VTContext.get();
13397}
13398
13400 if (!T)
13401 T = Target;
13402 switch (T->getCXXABI().getKind()) {
13403 case TargetCXXABI::AppleARM64:
13404 case TargetCXXABI::Fuchsia:
13405 case TargetCXXABI::GenericAArch64:
13406 case TargetCXXABI::GenericItanium:
13407 case TargetCXXABI::GenericARM:
13408 case TargetCXXABI::GenericMIPS:
13409 case TargetCXXABI::iOS:
13410 case TargetCXXABI::WebAssembly:
13411 case TargetCXXABI::WatchOS:
13412 case TargetCXXABI::XL:
13414 case TargetCXXABI::Microsoft:
13416 }
13417 llvm_unreachable("Unsupported ABI");
13418}
13419
13421 assert(T.getCXXABI().getKind() != TargetCXXABI::Microsoft &&
13422 "Device mangle context does not support Microsoft mangling.");
13423 switch (T.getCXXABI().getKind()) {
13424 case TargetCXXABI::AppleARM64:
13425 case TargetCXXABI::Fuchsia:
13426 case TargetCXXABI::GenericAArch64:
13427 case TargetCXXABI::GenericItanium:
13428 case TargetCXXABI::GenericARM:
13429 case TargetCXXABI::GenericMIPS:
13430 case TargetCXXABI::iOS:
13431 case TargetCXXABI::WebAssembly:
13432 case TargetCXXABI::WatchOS:
13433 case TargetCXXABI::XL:
13435 *this, getDiagnostics(),
13436 [](ASTContext &, const NamedDecl *ND) -> UnsignedOrNone {
13437 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
13438 return RD->getDeviceLambdaManglingNumber();
13439 return std::nullopt;
13440 },
13441 /*IsAux=*/true);
13442 case TargetCXXABI::Microsoft:
13444 /*IsAux=*/true);
13445 }
13446 llvm_unreachable("Unsupported ABI");
13447}
13448
13450 // If the host and device have different C++ ABIs, mark it as the device
13451 // mangle context so that the mangling needs to retrieve the additional
13452 // device lambda mangling number instead of the regular host one.
13453 if (getAuxTargetInfo() && getTargetInfo().getCXXABI().isMicrosoft() &&
13454 getAuxTargetInfo()->getCXXABI().isItaniumFamily()) {
13456 }
13457
13459}
13460
13461CXXABI::~CXXABI() = default;
13462
13464 return ASTRecordLayouts.getMemorySize() +
13465 llvm::capacity_in_bytes(ObjCLayouts) +
13466 llvm::capacity_in_bytes(KeyFunctions) +
13467 llvm::capacity_in_bytes(ObjCImpls) +
13468 llvm::capacity_in_bytes(BlockVarCopyInits) +
13469 llvm::capacity_in_bytes(DeclAttrs) +
13470 llvm::capacity_in_bytes(TemplateOrInstantiation) +
13471 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
13472 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
13473 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
13474 llvm::capacity_in_bytes(OverriddenMethods) +
13475 llvm::capacity_in_bytes(Types) +
13476 llvm::capacity_in_bytes(VariableArrayTypes);
13477}
13478
13479/// getIntTypeForBitwidth -
13480/// sets integer QualTy according to specified details:
13481/// bitwidth, signed/unsigned.
13482/// Returns empty type if there is no appropriate target types.
13484 unsigned Signed) const {
13486 CanQualType QualTy = getFromTargetType(Ty);
13487 if (!QualTy && DestWidth == 128)
13488 return Signed ? Int128Ty : UnsignedInt128Ty;
13489 return QualTy;
13490}
13491
13492/// getRealTypeForBitwidth -
13493/// sets floating point QualTy according to specified bitwidth.
13494/// Returns empty type if there is no appropriate target types.
13496 FloatModeKind ExplicitType) const {
13497 FloatModeKind Ty =
13498 getTargetInfo().getRealTypeByWidth(DestWidth, ExplicitType);
13499 switch (Ty) {
13501 return HalfTy;
13503 return FloatTy;
13505 return DoubleTy;
13507 return LongDoubleTy;
13509 return Float128Ty;
13511 return Ibm128Ty;
13513 return {};
13514 }
13515
13516 llvm_unreachable("Unhandled TargetInfo::RealType value");
13517}
13518
13519void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
13520 if (Number <= 1)
13521 return;
13522
13523 MangleNumbers[ND] = Number;
13524
13525 if (Listener)
13526 Listener->AddedManglingNumber(ND, Number);
13527}
13528
13530 bool ForAuxTarget) const {
13531 auto I = MangleNumbers.find(ND);
13532 unsigned Res = I != MangleNumbers.end() ? I->second : 1;
13533 // CUDA/HIP host compilation encodes host and device mangling numbers
13534 // as lower and upper half of 32 bit integer.
13535 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice) {
13536 Res = ForAuxTarget ? Res >> 16 : Res & 0xFFFF;
13537 } else {
13538 assert(!ForAuxTarget && "Only CUDA/HIP host compilation supports mangling "
13539 "number for aux target");
13540 }
13541 return Res > 1 ? Res : 1;
13542}
13543
13544void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
13545 if (Number <= 1)
13546 return;
13547
13548 StaticLocalNumbers[VD] = Number;
13549
13550 if (Listener)
13551 Listener->AddedStaticLocalNumbers(VD, Number);
13552}
13553
13555 auto I = StaticLocalNumbers.find(VD);
13556 return I != StaticLocalNumbers.end() ? I->second : 1;
13557}
13558
13560 bool IsDestroying) {
13561 if (!IsDestroying) {
13562 assert(!DestroyingOperatorDeletes.contains(FD->getCanonicalDecl()));
13563 return;
13564 }
13565 DestroyingOperatorDeletes.insert(FD->getCanonicalDecl());
13566}
13567
13569 return DestroyingOperatorDeletes.contains(FD->getCanonicalDecl());
13570}
13571
13573 bool IsTypeAware) {
13574 if (!IsTypeAware) {
13575 assert(!TypeAwareOperatorNewAndDeletes.contains(FD->getCanonicalDecl()));
13576 return;
13577 }
13578 TypeAwareOperatorNewAndDeletes.insert(FD->getCanonicalDecl());
13579}
13580
13582 return TypeAwareOperatorNewAndDeletes.contains(FD->getCanonicalDecl());
13583}
13584
13586 FunctionDecl *OperatorDelete,
13587 OperatorDeleteKind K) const {
13588 switch (K) {
13590 OperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] = OperatorDelete;
13591 break;
13593 GlobalOperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] =
13594 OperatorDelete;
13595 break;
13597 ArrayOperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] =
13598 OperatorDelete;
13599 break;
13601 GlobalArrayOperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] =
13602 OperatorDelete;
13603 break;
13604 }
13605}
13606
13608 OperatorDeleteKind K) const {
13609 switch (K) {
13611 return OperatorDeletesForVirtualDtor.contains(Dtor->getCanonicalDecl());
13613 return GlobalOperatorDeletesForVirtualDtor.contains(
13614 Dtor->getCanonicalDecl());
13616 return ArrayOperatorDeletesForVirtualDtor.contains(
13617 Dtor->getCanonicalDecl());
13619 return GlobalArrayOperatorDeletesForVirtualDtor.contains(
13620 Dtor->getCanonicalDecl());
13621 }
13622 return false;
13623}
13624
13627 OperatorDeleteKind K) const {
13628 const CXXDestructorDecl *Canon = Dtor->getCanonicalDecl();
13629 switch (K) {
13631 if (OperatorDeletesForVirtualDtor.contains(Canon))
13632 return OperatorDeletesForVirtualDtor[Canon];
13633 return nullptr;
13635 if (GlobalOperatorDeletesForVirtualDtor.contains(Canon))
13636 return GlobalOperatorDeletesForVirtualDtor[Canon];
13637 return nullptr;
13639 if (ArrayOperatorDeletesForVirtualDtor.contains(Canon))
13640 return ArrayOperatorDeletesForVirtualDtor[Canon];
13641 return nullptr;
13643 if (GlobalArrayOperatorDeletesForVirtualDtor.contains(Canon))
13644 return GlobalArrayOperatorDeletesForVirtualDtor[Canon];
13645 return nullptr;
13646 }
13647 return nullptr;
13648}
13649
13651 const CXXRecordDecl *RD) {
13652 if (!getTargetInfo().emitVectorDeletingDtors(getLangOpts()))
13653 return false;
13654
13655 return MaybeRequireVectorDeletingDtor.count(RD);
13656}
13657
13659 const CXXRecordDecl *RD) {
13660 if (!getTargetInfo().emitVectorDeletingDtors(getLangOpts()))
13661 return;
13662
13663 MaybeRequireVectorDeletingDtor.insert(RD);
13664}
13665
13668 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13669 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
13670 if (!MCtx)
13672 return *MCtx;
13673}
13674
13677 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13678 std::unique_ptr<MangleNumberingContext> &MCtx =
13679 ExtraMangleNumberingContexts[D];
13680 if (!MCtx)
13682 return *MCtx;
13683}
13684
13685std::unique_ptr<MangleNumberingContext>
13687 return ABI->createMangleNumberingContext();
13688}
13689
13690const CXXConstructorDecl *
13692 return ABI->getCopyConstructorForExceptionObject(
13694}
13695
13697 CXXConstructorDecl *CD) {
13698 return ABI->addCopyConstructorForExceptionObject(
13701}
13702
13704 TypedefNameDecl *DD) {
13705 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
13706}
13707
13710 return ABI->getTypedefNameForUnnamedTagDecl(TD);
13711}
13712
13714 DeclaratorDecl *DD) {
13715 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
13716}
13717
13719 return ABI->getDeclaratorForUnnamedTagDecl(TD);
13720}
13721
13723 ParamIndices[D] = index;
13724}
13725
13727 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
13728 assert(I != ParamIndices.end() &&
13729 "ParmIndices lacks entry set by ParmVarDecl");
13730 return I->second;
13731}
13732
13734 unsigned Length) const {
13735 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
13736 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
13737 EltTy = EltTy.withConst();
13738
13739 EltTy = adjustStringLiteralBaseType(EltTy);
13740
13741 // Get an array type for the string, according to C99 6.4.5. This includes
13742 // the null terminator character.
13743 return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr,
13744 ArraySizeModifier::Normal, /*IndexTypeQuals*/ 0);
13745}
13746
13749 StringLiteral *&Result = StringLiteralCache[Key];
13750 if (!Result)
13752 *this, Key, StringLiteralKind::Ordinary,
13753 /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()),
13754 SourceLocation());
13755 return Result;
13756}
13757
13758MSGuidDecl *
13760 assert(MSGuidTagDecl && "building MS GUID without MS extensions?");
13761
13762 llvm::FoldingSetNodeID ID;
13763 MSGuidDecl::Profile(ID, Parts);
13764
13765 void *InsertPos;
13766 if (MSGuidDecl *Existing = MSGuidDecls.FindNodeOrInsertPos(ID, InsertPos))
13767 return Existing;
13768
13769 QualType GUIDType = getMSGuidType().withConst();
13770 MSGuidDecl *New = MSGuidDecl::Create(*this, GUIDType, Parts);
13771 MSGuidDecls.InsertNode(New, InsertPos);
13772 return New;
13773}
13774
13777 const APValue &APVal) const {
13778 llvm::FoldingSetNodeID ID;
13780
13781 void *InsertPos;
13782 if (UnnamedGlobalConstantDecl *Existing =
13783 UnnamedGlobalConstantDecls.FindNodeOrInsertPos(ID, InsertPos))
13784 return Existing;
13785
13787 UnnamedGlobalConstantDecl::Create(*this, Ty, APVal);
13788 UnnamedGlobalConstantDecls.InsertNode(New, InsertPos);
13789 return New;
13790}
13791
13794 assert(T->isRecordType() && "template param object of unexpected type");
13795
13796 // C++ [temp.param]p8:
13797 // [...] a static storage duration object of type 'const T' [...]
13798 T.addConst();
13799
13800 llvm::FoldingSetNodeID ID;
13802
13803 void *InsertPos;
13804 if (TemplateParamObjectDecl *Existing =
13805 TemplateParamObjectDecls.FindNodeOrInsertPos(ID, InsertPos))
13806 return Existing;
13807
13808 TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(*this, T, V);
13809 TemplateParamObjectDecls.InsertNode(New, InsertPos);
13810 return New;
13811}
13812
13814 const llvm::Triple &T = getTargetInfo().getTriple();
13815 if (!T.isOSDarwin())
13816 return false;
13817
13818 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
13819 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
13820 return false;
13821
13822 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
13823 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
13824 uint64_t Size = sizeChars.getQuantity();
13825 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
13826 unsigned Align = alignChars.getQuantity();
13827 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
13828 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
13829}
13830
13831bool
13833 const ObjCMethodDecl *MethodImpl) {
13834 // No point trying to match an unavailable/deprecated mothod.
13835 if (MethodDecl->hasAttr<UnavailableAttr>()
13836 || MethodDecl->hasAttr<DeprecatedAttr>())
13837 return false;
13838 if (MethodDecl->getObjCDeclQualifier() !=
13839 MethodImpl->getObjCDeclQualifier())
13840 return false;
13841 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
13842 return false;
13843
13844 if (MethodDecl->param_size() != MethodImpl->param_size())
13845 return false;
13846
13847 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
13848 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
13849 EF = MethodDecl->param_end();
13850 IM != EM && IF != EF; ++IM, ++IF) {
13851 const ParmVarDecl *DeclVar = (*IF);
13852 const ParmVarDecl *ImplVar = (*IM);
13853 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
13854 return false;
13855 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
13856 return false;
13857 }
13858
13859 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
13860}
13861
13863 LangAS AS;
13865 AS = LangAS::Default;
13866 else
13867 AS = QT->getPointeeType().getAddressSpace();
13868
13870}
13871
13874}
13875
13876bool ASTContext::hasSameExpr(const Expr *X, const Expr *Y) const {
13877 if (X == Y)
13878 return true;
13879 if (!X || !Y)
13880 return false;
13881 llvm::FoldingSetNodeID IDX, IDY;
13882 X->Profile(IDX, *this, /*Canonical=*/true);
13883 Y->Profile(IDY, *this, /*Canonical=*/true);
13884 return IDX == IDY;
13885}
13886
13887// The getCommon* helpers return, for given 'same' X and Y entities given as
13888// inputs, another entity which is also the 'same' as the inputs, but which
13889// is closer to the canonical form of the inputs, each according to a given
13890// criteria.
13891// The getCommon*Checked variants are 'null inputs not-allowed' equivalents of
13892// the regular ones.
13893
13895 if (!declaresSameEntity(X, Y))
13896 return nullptr;
13897 for (const Decl *DX : X->redecls()) {
13898 // If we reach Y before reaching the first decl, that means X is older.
13899 if (DX == Y)
13900 return X;
13901 // If we reach the first decl, then Y is older.
13902 if (DX->isFirstDecl())
13903 return Y;
13904 }
13905 llvm_unreachable("Corrupt redecls chain");
13906}
13907
13908template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
13909static T *getCommonDecl(T *X, T *Y) {
13910 return cast_or_null<T>(
13911 getCommonDecl(const_cast<Decl *>(cast_or_null<Decl>(X)),
13912 const_cast<Decl *>(cast_or_null<Decl>(Y))));
13913}
13914
13915template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
13916static T *getCommonDeclChecked(T *X, T *Y) {
13917 return cast<T>(getCommonDecl(const_cast<Decl *>(cast<Decl>(X)),
13918 const_cast<Decl *>(cast<Decl>(Y))));
13919}
13920
13922 TemplateName Y,
13923 bool IgnoreDeduced = false) {
13924 if (X.getAsVoidPointer() == Y.getAsVoidPointer())
13925 return X;
13926 // FIXME: There are cases here where we could find a common template name
13927 // with more sugar. For example one could be a SubstTemplateTemplate*
13928 // replacing the other.
13929 TemplateName CX = Ctx.getCanonicalTemplateName(X, IgnoreDeduced);
13930 if (CX.getAsVoidPointer() !=
13932 return TemplateName();
13933 return CX;
13934}
13935
13938 bool IgnoreDeduced) {
13939 TemplateName R = getCommonTemplateName(Ctx, X, Y, IgnoreDeduced);
13940 assert(R.getAsVoidPointer() != nullptr);
13941 return R;
13942}
13943
13945 ArrayRef<QualType> Ys, bool Unqualified = false) {
13946 assert(Xs.size() == Ys.size());
13947 SmallVector<QualType, 8> Rs(Xs.size());
13948 for (size_t I = 0; I < Rs.size(); ++I)
13949 Rs[I] = Ctx.getCommonSugaredType(Xs[I], Ys[I], Unqualified);
13950 return Rs;
13951}
13952
13953template <class T>
13954static SourceLocation getCommonAttrLoc(const T *X, const T *Y) {
13955 return X->getAttributeLoc() == Y->getAttributeLoc() ? X->getAttributeLoc()
13956 : SourceLocation();
13957}
13958
13960 const TemplateArgument &X,
13961 const TemplateArgument &Y) {
13962 if (X.getKind() != Y.getKind())
13963 return TemplateArgument();
13964
13965 switch (X.getKind()) {
13967 if (!Ctx.hasSameType(X.getAsType(), Y.getAsType()))
13968 return TemplateArgument();
13969 return TemplateArgument(
13970 Ctx.getCommonSugaredType(X.getAsType(), Y.getAsType()));
13972 if (!Ctx.hasSameType(X.getNullPtrType(), Y.getNullPtrType()))
13973 return TemplateArgument();
13974 return TemplateArgument(
13975 Ctx.getCommonSugaredType(X.getNullPtrType(), Y.getNullPtrType()),
13976 /*Unqualified=*/true);
13978 if (!Ctx.hasSameType(X.getAsExpr()->getType(), Y.getAsExpr()->getType()))
13979 return TemplateArgument();
13980 // FIXME: Try to keep the common sugar.
13981 return X;
13983 TemplateName TX = X.getAsTemplate(), TY = Y.getAsTemplate();
13984 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
13985 if (!CTN.getAsVoidPointer())
13986 return TemplateArgument();
13987 return TemplateArgument(CTN);
13988 }
13990 TemplateName TX = X.getAsTemplateOrTemplatePattern(),
13992 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
13993 if (!CTN.getAsVoidPointer())
13994 return TemplateName();
13995 auto NExpX = X.getNumTemplateExpansions();
13996 assert(NExpX == Y.getNumTemplateExpansions());
13997 return TemplateArgument(CTN, NExpX);
13998 }
13999 default:
14000 // FIXME: Handle the other argument kinds.
14001 return X;
14002 }
14003}
14004
14009 if (Xs.size() != Ys.size())
14010 return true;
14011 R.resize(Xs.size());
14012 for (size_t I = 0; I < R.size(); ++I) {
14013 R[I] = getCommonTemplateArgument(Ctx, Xs[I], Ys[I]);
14014 if (R[I].isNull())
14015 return true;
14016 }
14017 return false;
14018}
14019
14024 bool Different = getCommonTemplateArguments(Ctx, R, Xs, Ys);
14025 assert(!Different);
14026 (void)Different;
14027 return R;
14028}
14029
14030template <class T>
14032 bool IsSame) {
14033 ElaboratedTypeKeyword KX = X->getKeyword(), KY = Y->getKeyword();
14034 if (KX == KY)
14035 return KX;
14037 assert(!IsSame || KX == getCanonicalElaboratedTypeKeyword(KY));
14038 return KX;
14039}
14040
14041/// Returns a NestedNameSpecifier which has only the common sugar
14042/// present in both NNS1 and NNS2.
14045 NestedNameSpecifier NNS2, bool IsSame) {
14046 // If they are identical, all sugar is common.
14047 if (NNS1 == NNS2)
14048 return NNS1;
14049
14050 // IsSame implies both Qualifiers are equivalent.
14051 NestedNameSpecifier Canon = NNS1.getCanonical();
14052 if (Canon != NNS2.getCanonical()) {
14053 assert(!IsSame && "Should be the same NestedNameSpecifier");
14054 // If they are not the same, there is nothing to unify.
14055 return std::nullopt;
14056 }
14057
14058 NestedNameSpecifier R = std::nullopt;
14059 NestedNameSpecifier::Kind Kind = NNS1.getKind();
14060 assert(Kind == NNS2.getKind());
14061 switch (Kind) {
14063 auto [Namespace1, Prefix1] = NNS1.getAsNamespaceAndPrefix();
14064 auto [Namespace2, Prefix2] = NNS2.getAsNamespaceAndPrefix();
14065 auto Kind = Namespace1->getKind();
14066 if (Kind != Namespace2->getKind() ||
14067 (Kind == Decl::NamespaceAlias &&
14068 !declaresSameEntity(Namespace1, Namespace2))) {
14070 Ctx,
14071 ::getCommonDeclChecked(Namespace1->getNamespace(),
14072 Namespace2->getNamespace()),
14073 /*Prefix=*/std::nullopt);
14074 break;
14075 }
14076 // The prefixes for namespaces are not significant, its declaration
14077 // identifies it uniquely.
14078 NestedNameSpecifier Prefix = ::getCommonNNS(Ctx, Prefix1, Prefix2,
14079 /*IsSame=*/false);
14080 R = NestedNameSpecifier(Ctx, ::getCommonDeclChecked(Namespace1, Namespace2),
14081 Prefix);
14082 break;
14083 }
14085 const Type *T1 = NNS1.getAsType(), *T2 = NNS2.getAsType();
14086 const Type *T = Ctx.getCommonSugaredType(QualType(T1, 0), QualType(T2, 0),
14087 /*Unqualified=*/true)
14088 .getTypePtr();
14089 R = NestedNameSpecifier(T);
14090 break;
14091 }
14093 // FIXME: Can __super even be used with data members?
14094 // If it's only usable in functions, we will never see it here,
14095 // unless we save the qualifiers used in function types.
14096 // In that case, it might be possible NNS2 is a type,
14097 // in which case we should degrade the result to
14098 // a CXXRecordType.
14100 NNS2.getAsMicrosoftSuper()));
14101 break;
14102 }
14105 // These are singletons.
14106 llvm_unreachable("singletons did not compare equal");
14107 }
14108 assert(R.getCanonical() == Canon);
14109 return R;
14110}
14111
14112template <class T>
14114 const T *Y, bool IsSame) {
14115 return ::getCommonNNS(Ctx, X->getQualifier(), Y->getQualifier(), IsSame);
14116}
14117
14118template <class T>
14119static QualType getCommonElementType(const ASTContext &Ctx, const T *X,
14120 const T *Y) {
14121 return Ctx.getCommonSugaredType(X->getElementType(), Y->getElementType());
14122}
14123
14125 QualType X, QualType Y,
14126 Qualifiers &QX,
14127 Qualifiers &QY) {
14128 QualType R = Ctx.getCommonSugaredType(X, Y,
14129 /*Unqualified=*/true);
14130 // Qualifiers common to both element types.
14131 Qualifiers RQ = R.getQualifiers();
14132 // For each side, move to the top level any qualifiers which are not common to
14133 // both element types. The caller must assume top level qualifiers might
14134 // be different, even if they are the same type, and can be treated as sugar.
14135 QX += X.getQualifiers() - RQ;
14136 QY += Y.getQualifiers() - RQ;
14137 return R;
14138}
14139
14140template <class T>
14142 Qualifiers &QX, const T *Y,
14143 Qualifiers &QY) {
14144 return getCommonTypeWithQualifierLifting(Ctx, X->getElementType(),
14145 Y->getElementType(), QX, QY);
14146}
14147
14148template <class T>
14149static QualType getCommonPointeeType(const ASTContext &Ctx, const T *X,
14150 const T *Y) {
14151 return Ctx.getCommonSugaredType(X->getPointeeType(), Y->getPointeeType());
14152}
14153
14154template <class T>
14155static auto *getCommonSizeExpr(const ASTContext &Ctx, T *X, T *Y) {
14156 assert(Ctx.hasSameExpr(X->getSizeExpr(), Y->getSizeExpr()));
14157 return X->getSizeExpr();
14158}
14159
14160static auto getCommonSizeModifier(const ArrayType *X, const ArrayType *Y) {
14161 assert(X->getSizeModifier() == Y->getSizeModifier());
14162 return X->getSizeModifier();
14163}
14164
14166 const ArrayType *Y) {
14167 assert(X->getIndexTypeCVRQualifiers() == Y->getIndexTypeCVRQualifiers());
14168 return X->getIndexTypeCVRQualifiers();
14169}
14170
14171// Merges two type lists such that the resulting vector will contain
14172// each type (in a canonical sense) only once, in the order they appear
14173// from X to Y. If they occur in both X and Y, the result will contain
14174// the common sugared type between them.
14175static void mergeTypeLists(const ASTContext &Ctx,
14178 llvm::DenseMap<QualType, unsigned> Found;
14179 for (auto Ts : {X, Y}) {
14180 for (QualType T : Ts) {
14181 auto Res = Found.try_emplace(Ctx.getCanonicalType(T), Out.size());
14182 if (!Res.second) {
14183 QualType &U = Out[Res.first->second];
14184 U = Ctx.getCommonSugaredType(U, T);
14185 } else {
14186 Out.emplace_back(T);
14187 }
14188 }
14189 }
14190}
14191
14192FunctionProtoType::ExceptionSpecInfo
14195 SmallVectorImpl<QualType> &ExceptionTypeStorage,
14196 bool AcceptDependent) const {
14197 ExceptionSpecificationType EST1 = ESI1.Type, EST2 = ESI2.Type;
14198
14199 // If either of them can throw anything, that is the result.
14200 for (auto I : {EST_None, EST_MSAny, EST_NoexceptFalse}) {
14201 if (EST1 == I)
14202 return ESI1;
14203 if (EST2 == I)
14204 return ESI2;
14205 }
14206
14207 // If either of them is non-throwing, the result is the other.
14208 for (auto I :
14210 if (EST1 == I)
14211 return ESI2;
14212 if (EST2 == I)
14213 return ESI1;
14214 }
14215
14216 // If we're left with value-dependent computed noexcept expressions, we're
14217 // stuck. Before C++17, we can just drop the exception specification entirely,
14218 // since it's not actually part of the canonical type. And this should never
14219 // happen in C++17, because it would mean we were computing the composite
14220 // pointer type of dependent types, which should never happen.
14221 if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) {
14222 assert(AcceptDependent &&
14223 "computing composite pointer type of dependent types");
14225 }
14226
14227 // Switch over the possibilities so that people adding new values know to
14228 // update this function.
14229 switch (EST1) {
14230 case EST_None:
14231 case EST_DynamicNone:
14232 case EST_MSAny:
14233 case EST_BasicNoexcept:
14235 case EST_NoexceptFalse:
14236 case EST_NoexceptTrue:
14237 case EST_NoThrow:
14238 llvm_unreachable("These ESTs should be handled above");
14239
14240 case EST_Dynamic: {
14241 // This is the fun case: both exception specifications are dynamic. Form
14242 // the union of the two lists.
14243 assert(EST2 == EST_Dynamic && "other cases should already be handled");
14244 mergeTypeLists(*this, ExceptionTypeStorage, ESI1.Exceptions,
14245 ESI2.Exceptions);
14247 Result.Exceptions = ExceptionTypeStorage;
14248 return Result;
14249 }
14250
14251 case EST_Unevaluated:
14252 case EST_Uninstantiated:
14253 case EST_Unparsed:
14254 llvm_unreachable("shouldn't see unresolved exception specifications here");
14255 }
14256
14257 llvm_unreachable("invalid ExceptionSpecificationType");
14258}
14259
14261 Qualifiers &QX, const Type *Y,
14262 Qualifiers &QY) {
14263 Type::TypeClass TC = X->getTypeClass();
14264 assert(TC == Y->getTypeClass());
14265 switch (TC) {
14266#define UNEXPECTED_TYPE(Class, Kind) \
14267 case Type::Class: \
14268 llvm_unreachable("Unexpected " Kind ": " #Class);
14269
14270#define NON_CANONICAL_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "non-canonical")
14271#define TYPE(Class, Base)
14272#include "clang/AST/TypeNodes.inc"
14273
14274#define SUGAR_FREE_TYPE(Class) UNEXPECTED_TYPE(Class, "sugar-free")
14276 SUGAR_FREE_TYPE(DeducedTemplateSpecialization)
14277 SUGAR_FREE_TYPE(DependentBitInt)
14279 SUGAR_FREE_TYPE(ObjCInterface)
14280 SUGAR_FREE_TYPE(SubstTemplateTypeParmPack)
14281 SUGAR_FREE_TYPE(SubstBuiltinTemplatePack)
14282 SUGAR_FREE_TYPE(UnresolvedUsing)
14283 SUGAR_FREE_TYPE(HLSLAttributedResource)
14284 SUGAR_FREE_TYPE(HLSLInlineSpirv)
14285#undef SUGAR_FREE_TYPE
14286#define NON_UNIQUE_TYPE(Class) UNEXPECTED_TYPE(Class, "non-unique")
14287 NON_UNIQUE_TYPE(TypeOfExpr)
14288 NON_UNIQUE_TYPE(VariableArray)
14289#undef NON_UNIQUE_TYPE
14290
14291 UNEXPECTED_TYPE(TypeOf, "sugar")
14292
14293#undef UNEXPECTED_TYPE
14294
14295 case Type::Auto: {
14296 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
14297 assert(AX->getDeducedKind() == AY->getDeducedKind());
14298 assert(AX->getDeducedKind() != DeducedKind::Deduced);
14299 assert(AX->getKeyword() == AY->getKeyword());
14300 TemplateDecl *CD = ::getCommonDecl(AX->getTypeConstraintConcept(),
14301 AY->getTypeConstraintConcept());
14303 if (CD &&
14304 getCommonTemplateArguments(Ctx, As, AX->getTypeConstraintArguments(),
14305 AY->getTypeConstraintArguments())) {
14306 CD = nullptr; // The arguments differ, so make it unconstrained.
14307 As.clear();
14308 }
14309 return Ctx.getAutoType(AX->getDeducedKind(), QualType(), AX->getKeyword(),
14310 CD, As);
14311 }
14312 case Type::IncompleteArray: {
14313 const auto *AX = cast<IncompleteArrayType>(X),
14315 return Ctx.getIncompleteArrayType(
14316 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
14318 }
14319 case Type::DependentSizedArray: {
14320 const auto *AX = cast<DependentSizedArrayType>(X),
14322 return Ctx.getDependentSizedArrayType(
14323 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
14324 getCommonSizeExpr(Ctx, AX, AY), getCommonSizeModifier(AX, AY),
14326 }
14327 case Type::ConstantArray: {
14328 const auto *AX = cast<ConstantArrayType>(X),
14329 *AY = cast<ConstantArrayType>(Y);
14330 assert(AX->getSize() == AY->getSize());
14331 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
14332 ? AX->getSizeExpr()
14333 : nullptr;
14334 return Ctx.getConstantArrayType(
14335 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
14337 }
14338 case Type::ArrayParameter: {
14339 const auto *AX = cast<ArrayParameterType>(X),
14340 *AY = cast<ArrayParameterType>(Y);
14341 assert(AX->getSize() == AY->getSize());
14342 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
14343 ? AX->getSizeExpr()
14344 : nullptr;
14345 auto ArrayTy = Ctx.getConstantArrayType(
14346 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
14348 return Ctx.getArrayParameterType(ArrayTy);
14349 }
14350 case Type::Atomic: {
14351 const auto *AX = cast<AtomicType>(X), *AY = cast<AtomicType>(Y);
14352 return Ctx.getAtomicType(
14353 Ctx.getCommonSugaredType(AX->getValueType(), AY->getValueType()));
14354 }
14355 case Type::Complex: {
14356 const auto *CX = cast<ComplexType>(X), *CY = cast<ComplexType>(Y);
14357 return Ctx.getComplexType(getCommonArrayElementType(Ctx, CX, QX, CY, QY));
14358 }
14359 case Type::Pointer: {
14360 const auto *PX = cast<PointerType>(X), *PY = cast<PointerType>(Y);
14361 return Ctx.getPointerType(getCommonPointeeType(Ctx, PX, PY));
14362 }
14363 case Type::BlockPointer: {
14364 const auto *PX = cast<BlockPointerType>(X), *PY = cast<BlockPointerType>(Y);
14365 return Ctx.getBlockPointerType(getCommonPointeeType(Ctx, PX, PY));
14366 }
14367 case Type::ObjCObjectPointer: {
14368 const auto *PX = cast<ObjCObjectPointerType>(X),
14370 return Ctx.getObjCObjectPointerType(getCommonPointeeType(Ctx, PX, PY));
14371 }
14372 case Type::MemberPointer: {
14373 const auto *PX = cast<MemberPointerType>(X),
14374 *PY = cast<MemberPointerType>(Y);
14375 assert(declaresSameEntity(PX->getMostRecentCXXRecordDecl(),
14376 PY->getMostRecentCXXRecordDecl()));
14377 return Ctx.getMemberPointerType(
14378 getCommonPointeeType(Ctx, PX, PY),
14379 getCommonQualifier(Ctx, PX, PY, /*IsSame=*/true),
14380 PX->getMostRecentCXXRecordDecl());
14381 }
14382 case Type::LValueReference: {
14383 const auto *PX = cast<LValueReferenceType>(X),
14385 // FIXME: Preserve PointeeTypeAsWritten.
14386 return Ctx.getLValueReferenceType(getCommonPointeeType(Ctx, PX, PY),
14387 PX->isSpelledAsLValue() ||
14388 PY->isSpelledAsLValue());
14389 }
14390 case Type::RValueReference: {
14391 const auto *PX = cast<RValueReferenceType>(X),
14393 // FIXME: Preserve PointeeTypeAsWritten.
14394 return Ctx.getRValueReferenceType(getCommonPointeeType(Ctx, PX, PY));
14395 }
14396 case Type::DependentAddressSpace: {
14397 const auto *PX = cast<DependentAddressSpaceType>(X),
14399 assert(Ctx.hasSameExpr(PX->getAddrSpaceExpr(), PY->getAddrSpaceExpr()));
14400 return Ctx.getDependentAddressSpaceType(getCommonPointeeType(Ctx, PX, PY),
14401 PX->getAddrSpaceExpr(),
14402 getCommonAttrLoc(PX, PY));
14403 }
14404 case Type::FunctionNoProto: {
14405 const auto *FX = cast<FunctionNoProtoType>(X),
14407 assert(FX->getExtInfo() == FY->getExtInfo());
14408 return Ctx.getFunctionNoProtoType(
14409 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType()),
14410 FX->getExtInfo());
14411 }
14412 case Type::FunctionProto: {
14413 const auto *FX = cast<FunctionProtoType>(X),
14414 *FY = cast<FunctionProtoType>(Y);
14415 FunctionProtoType::ExtProtoInfo EPIX = FX->getExtProtoInfo(),
14416 EPIY = FY->getExtProtoInfo();
14417 assert(EPIX.ExtInfo == EPIY.ExtInfo);
14418 assert(!EPIX.ExtParameterInfos == !EPIY.ExtParameterInfos);
14419 assert(!EPIX.ExtParameterInfos ||
14420 llvm::equal(
14421 llvm::ArrayRef(EPIX.ExtParameterInfos, FX->getNumParams()),
14422 llvm::ArrayRef(EPIY.ExtParameterInfos, FY->getNumParams())));
14423 assert(EPIX.RefQualifier == EPIY.RefQualifier);
14424 assert(EPIX.TypeQuals == EPIY.TypeQuals);
14425 assert(EPIX.Variadic == EPIY.Variadic);
14426
14427 // FIXME: Can we handle an empty EllipsisLoc?
14428 // Use emtpy EllipsisLoc if X and Y differ.
14429
14430 EPIX.HasTrailingReturn = EPIX.HasTrailingReturn && EPIY.HasTrailingReturn;
14431
14432 QualType R =
14433 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType());
14434 auto P = getCommonTypes(Ctx, FX->param_types(), FY->param_types(),
14435 /*Unqualified=*/true);
14436
14437 SmallVector<QualType, 8> Exceptions;
14439 EPIX.ExceptionSpec, EPIY.ExceptionSpec, Exceptions, true);
14440 return Ctx.getFunctionType(R, P, EPIX);
14441 }
14442 case Type::ObjCObject: {
14443 const auto *OX = cast<ObjCObjectType>(X), *OY = cast<ObjCObjectType>(Y);
14444 assert(
14445 std::equal(OX->getProtocols().begin(), OX->getProtocols().end(),
14446 OY->getProtocols().begin(), OY->getProtocols().end(),
14447 [](const ObjCProtocolDecl *P0, const ObjCProtocolDecl *P1) {
14448 return P0->getCanonicalDecl() == P1->getCanonicalDecl();
14449 }) &&
14450 "protocol lists must be the same");
14451 auto TAs = getCommonTypes(Ctx, OX->getTypeArgsAsWritten(),
14452 OY->getTypeArgsAsWritten());
14453 return Ctx.getObjCObjectType(
14454 Ctx.getCommonSugaredType(OX->getBaseType(), OY->getBaseType()), TAs,
14455 OX->getProtocols(),
14456 OX->isKindOfTypeAsWritten() && OY->isKindOfTypeAsWritten());
14457 }
14458 case Type::ConstantMatrix: {
14459 const auto *MX = cast<ConstantMatrixType>(X),
14460 *MY = cast<ConstantMatrixType>(Y);
14461 assert(MX->getNumRows() == MY->getNumRows());
14462 assert(MX->getNumColumns() == MY->getNumColumns());
14463 return Ctx.getConstantMatrixType(getCommonElementType(Ctx, MX, MY),
14464 MX->getNumRows(), MX->getNumColumns());
14465 }
14466 case Type::DependentSizedMatrix: {
14467 const auto *MX = cast<DependentSizedMatrixType>(X),
14469 assert(Ctx.hasSameExpr(MX->getRowExpr(), MY->getRowExpr()));
14470 assert(Ctx.hasSameExpr(MX->getColumnExpr(), MY->getColumnExpr()));
14471 return Ctx.getDependentSizedMatrixType(
14472 getCommonElementType(Ctx, MX, MY), MX->getRowExpr(),
14473 MX->getColumnExpr(), getCommonAttrLoc(MX, MY));
14474 }
14475 case Type::Vector: {
14476 const auto *VX = cast<VectorType>(X), *VY = cast<VectorType>(Y);
14477 assert(VX->getNumElements() == VY->getNumElements());
14478 assert(VX->getVectorKind() == VY->getVectorKind());
14479 return Ctx.getVectorType(getCommonElementType(Ctx, VX, VY),
14480 VX->getNumElements(), VX->getVectorKind());
14481 }
14482 case Type::ExtVector: {
14483 const auto *VX = cast<ExtVectorType>(X), *VY = cast<ExtVectorType>(Y);
14484 assert(VX->getNumElements() == VY->getNumElements());
14485 return Ctx.getExtVectorType(getCommonElementType(Ctx, VX, VY),
14486 VX->getNumElements());
14487 }
14488 case Type::DependentSizedExtVector: {
14489 const auto *VX = cast<DependentSizedExtVectorType>(X),
14492 getCommonSizeExpr(Ctx, VX, VY),
14493 getCommonAttrLoc(VX, VY));
14494 }
14495 case Type::DependentVector: {
14496 const auto *VX = cast<DependentVectorType>(X),
14498 assert(VX->getVectorKind() == VY->getVectorKind());
14499 return Ctx.getDependentVectorType(
14500 getCommonElementType(Ctx, VX, VY), getCommonSizeExpr(Ctx, VX, VY),
14501 getCommonAttrLoc(VX, VY), VX->getVectorKind());
14502 }
14503 case Type::Enum:
14504 case Type::Record:
14505 case Type::InjectedClassName: {
14506 const auto *TX = cast<TagType>(X), *TY = cast<TagType>(Y);
14507 return Ctx.getTagType(::getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14508 ::getCommonQualifier(Ctx, TX, TY, /*IsSame=*/false),
14509 ::getCommonDeclChecked(TX->getDecl(), TY->getDecl()),
14510 /*OwnedTag=*/false);
14511 }
14512 case Type::TemplateSpecialization: {
14513 const auto *TX = cast<TemplateSpecializationType>(X),
14515 auto As = getCommonTemplateArguments(Ctx, TX->template_arguments(),
14516 TY->template_arguments());
14518 getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14519 ::getCommonTemplateNameChecked(Ctx, TX->getTemplateName(),
14520 TY->getTemplateName(),
14521 /*IgnoreDeduced=*/true),
14522 As, /*CanonicalArgs=*/{}, X->getCanonicalTypeInternal());
14523 }
14524 case Type::Decltype: {
14525 const auto *DX = cast<DecltypeType>(X);
14526 [[maybe_unused]] const auto *DY = cast<DecltypeType>(Y);
14527 assert(DX->isDependentType());
14528 assert(DY->isDependentType());
14529 assert(Ctx.hasSameExpr(DX->getUnderlyingExpr(), DY->getUnderlyingExpr()));
14530 // As Decltype is not uniqued, building a common type would be wasteful.
14531 return QualType(DX, 0);
14532 }
14533 case Type::PackIndexing: {
14534 const auto *DX = cast<PackIndexingType>(X);
14535 [[maybe_unused]] const auto *DY = cast<PackIndexingType>(Y);
14536 assert(DX->isDependentType());
14537 assert(DY->isDependentType());
14538 assert(Ctx.hasSameExpr(DX->getIndexExpr(), DY->getIndexExpr()));
14539 return QualType(DX, 0);
14540 }
14541 case Type::DependentName: {
14542 const auto *NX = cast<DependentNameType>(X),
14543 *NY = cast<DependentNameType>(Y);
14544 assert(NX->getIdentifier() == NY->getIdentifier());
14545 return Ctx.getDependentNameType(
14546 getCommonTypeKeyword(NX, NY, /*IsSame=*/true),
14547 getCommonQualifier(Ctx, NX, NY, /*IsSame=*/true), NX->getIdentifier());
14548 }
14549 case Type::OverflowBehavior: {
14550 const auto *NX = cast<OverflowBehaviorType>(X),
14552 assert(NX->getBehaviorKind() == NY->getBehaviorKind());
14553 return Ctx.getOverflowBehaviorType(
14554 NX->getBehaviorKind(),
14555 getCommonTypeWithQualifierLifting(Ctx, NX->getUnderlyingType(),
14556 NY->getUnderlyingType(), QX, QY));
14557 }
14558 case Type::UnaryTransform: {
14559 const auto *TX = cast<UnaryTransformType>(X),
14560 *TY = cast<UnaryTransformType>(Y);
14561 assert(TX->getUTTKind() == TY->getUTTKind());
14562 return Ctx.getUnaryTransformType(
14563 Ctx.getCommonSugaredType(TX->getBaseType(), TY->getBaseType()),
14564 Ctx.getCommonSugaredType(TX->getUnderlyingType(),
14565 TY->getUnderlyingType()),
14566 TX->getUTTKind());
14567 }
14568 case Type::PackExpansion: {
14569 const auto *PX = cast<PackExpansionType>(X),
14570 *PY = cast<PackExpansionType>(Y);
14571 assert(PX->getNumExpansions() == PY->getNumExpansions());
14572 return Ctx.getPackExpansionType(
14573 Ctx.getCommonSugaredType(PX->getPattern(), PY->getPattern()),
14574 PX->getNumExpansions(), false);
14575 }
14576 case Type::Pipe: {
14577 const auto *PX = cast<PipeType>(X), *PY = cast<PipeType>(Y);
14578 assert(PX->isReadOnly() == PY->isReadOnly());
14579 auto MP = PX->isReadOnly() ? &ASTContext::getReadPipeType
14581 return (Ctx.*MP)(getCommonElementType(Ctx, PX, PY));
14582 }
14583 case Type::TemplateTypeParm: {
14584 const auto *TX = cast<TemplateTypeParmType>(X),
14586 assert(TX->getDepth() == TY->getDepth());
14587 assert(TX->getIndex() == TY->getIndex());
14588 assert(TX->isParameterPack() == TY->isParameterPack());
14589 return Ctx.getTemplateTypeParmType(
14590 TX->getDepth(), TX->getIndex(), TX->isParameterPack(),
14591 getCommonDecl(TX->getDecl(), TY->getDecl()));
14592 }
14593 }
14594 llvm_unreachable("Unknown Type Class");
14595}
14596
14598 const Type *Y,
14599 SplitQualType Underlying) {
14600 Type::TypeClass TC = X->getTypeClass();
14601 if (TC != Y->getTypeClass())
14602 return QualType();
14603 switch (TC) {
14604#define UNEXPECTED_TYPE(Class, Kind) \
14605 case Type::Class: \
14606 llvm_unreachable("Unexpected " Kind ": " #Class);
14607#define TYPE(Class, Base)
14608#define DEPENDENT_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "dependent")
14609#include "clang/AST/TypeNodes.inc"
14610
14611#define CANONICAL_TYPE(Class) UNEXPECTED_TYPE(Class, "canonical")
14614 CANONICAL_TYPE(BlockPointer)
14617 CANONICAL_TYPE(ConstantArray)
14618 CANONICAL_TYPE(ArrayParameter)
14619 CANONICAL_TYPE(ConstantMatrix)
14621 CANONICAL_TYPE(ExtVector)
14622 CANONICAL_TYPE(FunctionNoProto)
14623 CANONICAL_TYPE(FunctionProto)
14624 CANONICAL_TYPE(IncompleteArray)
14625 CANONICAL_TYPE(HLSLAttributedResource)
14626 CANONICAL_TYPE(HLSLInlineSpirv)
14627 CANONICAL_TYPE(LValueReference)
14628 CANONICAL_TYPE(ObjCInterface)
14629 CANONICAL_TYPE(ObjCObject)
14630 CANONICAL_TYPE(ObjCObjectPointer)
14631 CANONICAL_TYPE(OverflowBehavior)
14635 CANONICAL_TYPE(RValueReference)
14636 CANONICAL_TYPE(VariableArray)
14638#undef CANONICAL_TYPE
14639
14640#undef UNEXPECTED_TYPE
14641
14642 case Type::Adjusted: {
14643 const auto *AX = cast<AdjustedType>(X), *AY = cast<AdjustedType>(Y);
14644 QualType OX = AX->getOriginalType(), OY = AY->getOriginalType();
14645 if (!Ctx.hasSameType(OX, OY))
14646 return QualType();
14647 // FIXME: It's inefficient to have to unify the original types.
14648 return Ctx.getAdjustedType(Ctx.getCommonSugaredType(OX, OY),
14649 Ctx.getQualifiedType(Underlying));
14650 }
14651 case Type::Decayed: {
14652 const auto *DX = cast<DecayedType>(X), *DY = cast<DecayedType>(Y);
14653 QualType OX = DX->getOriginalType(), OY = DY->getOriginalType();
14654 if (!Ctx.hasSameType(OX, OY))
14655 return QualType();
14656 // FIXME: It's inefficient to have to unify the original types.
14657 return Ctx.getDecayedType(Ctx.getCommonSugaredType(OX, OY),
14658 Ctx.getQualifiedType(Underlying));
14659 }
14660 case Type::Attributed: {
14661 const auto *AX = cast<AttributedType>(X), *AY = cast<AttributedType>(Y);
14662 AttributedType::Kind Kind = AX->getAttrKind();
14663 if (Kind != AY->getAttrKind())
14664 return QualType();
14665 QualType MX = AX->getModifiedType(), MY = AY->getModifiedType();
14666 if (!Ctx.hasSameType(MX, MY))
14667 return QualType();
14668 // FIXME: It's inefficient to have to unify the modified types.
14669 return Ctx.getAttributedType(Kind, Ctx.getCommonSugaredType(MX, MY),
14670 Ctx.getQualifiedType(Underlying),
14671 AX->getAttr());
14672 }
14673 case Type::BTFTagAttributed: {
14674 const auto *BX = cast<BTFTagAttributedType>(X);
14675 const BTFTypeTagAttr *AX = BX->getAttr();
14676 // The attribute is not uniqued, so just compare the tag.
14677 if (AX->getBTFTypeTag() !=
14678 cast<BTFTagAttributedType>(Y)->getAttr()->getBTFTypeTag())
14679 return QualType();
14680 return Ctx.getBTFTagAttributedType(AX, Ctx.getQualifiedType(Underlying));
14681 }
14682 case Type::Auto: {
14683 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
14684 assert(AX->getDeducedKind() == DeducedKind::Deduced);
14685 assert(AY->getDeducedKind() == DeducedKind::Deduced);
14686
14687 AutoTypeKeyword KW = AX->getKeyword();
14688 if (KW != AY->getKeyword())
14689 return QualType();
14690
14691 TemplateDecl *CD = ::getCommonDecl(AX->getTypeConstraintConcept(),
14692 AY->getTypeConstraintConcept());
14694 if (CD &&
14695 getCommonTemplateArguments(Ctx, As, AX->getTypeConstraintArguments(),
14696 AY->getTypeConstraintArguments())) {
14697 CD = nullptr; // The arguments differ, so make it unconstrained.
14698 As.clear();
14699 }
14700
14701 // Both auto types can't be dependent, otherwise they wouldn't have been
14702 // sugar. This implies they can't contain unexpanded packs either.
14704 Ctx.getQualifiedType(Underlying), AX->getKeyword(),
14705 CD, As);
14706 }
14707 case Type::PackIndexing:
14708 case Type::Decltype:
14709 return QualType();
14710 case Type::DeducedTemplateSpecialization:
14711 // FIXME: Try to merge these.
14712 return QualType();
14713 case Type::MacroQualified: {
14714 const auto *MX = cast<MacroQualifiedType>(X),
14715 *MY = cast<MacroQualifiedType>(Y);
14716 const IdentifierInfo *IX = MX->getMacroIdentifier();
14717 if (IX != MY->getMacroIdentifier())
14718 return QualType();
14719 return Ctx.getMacroQualifiedType(Ctx.getQualifiedType(Underlying), IX);
14720 }
14721 case Type::SubstTemplateTypeParm: {
14722 const auto *SX = cast<SubstTemplateTypeParmType>(X),
14724 Decl *CD =
14725 ::getCommonDecl(SX->getAssociatedDecl(), SY->getAssociatedDecl());
14726 if (!CD)
14727 return QualType();
14728 unsigned Index = SX->getIndex();
14729 if (Index != SY->getIndex())
14730 return QualType();
14731 auto PackIndex = SX->getPackIndex();
14732 if (PackIndex != SY->getPackIndex())
14733 return QualType();
14734 return Ctx.getSubstTemplateTypeParmType(Ctx.getQualifiedType(Underlying),
14735 CD, Index, PackIndex,
14736 SX->getFinal() && SY->getFinal());
14737 }
14738 case Type::ObjCTypeParam:
14739 // FIXME: Try to merge these.
14740 return QualType();
14741 case Type::Paren:
14742 return Ctx.getParenType(Ctx.getQualifiedType(Underlying));
14743
14744 case Type::TemplateSpecialization: {
14745 const auto *TX = cast<TemplateSpecializationType>(X),
14747 TemplateName CTN =
14748 ::getCommonTemplateName(Ctx, TX->getTemplateName(),
14749 TY->getTemplateName(), /*IgnoreDeduced=*/true);
14750 if (!CTN.getAsVoidPointer())
14751 return QualType();
14753 if (getCommonTemplateArguments(Ctx, As, TX->template_arguments(),
14754 TY->template_arguments()))
14755 return QualType();
14757 getCommonTypeKeyword(TX, TY, /*IsSame=*/false), CTN, As,
14758 /*CanonicalArgs=*/{}, Ctx.getQualifiedType(Underlying));
14759 }
14760 case Type::Typedef: {
14761 const auto *TX = cast<TypedefType>(X), *TY = cast<TypedefType>(Y);
14762 const TypedefNameDecl *CD = ::getCommonDecl(TX->getDecl(), TY->getDecl());
14763 if (!CD)
14764 return QualType();
14765 return Ctx.getTypedefType(
14766 ::getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14767 ::getCommonQualifier(Ctx, TX, TY, /*IsSame=*/false), CD,
14768 Ctx.getQualifiedType(Underlying));
14769 }
14770 case Type::TypeOf: {
14771 // The common sugar between two typeof expressions, where one is
14772 // potentially a typeof_unqual and the other is not, we unify to the
14773 // qualified type as that retains the most information along with the type.
14774 // We only return a typeof_unqual type when both types are unqual types.
14779 return Ctx.getTypeOfType(Ctx.getQualifiedType(Underlying), Kind);
14780 }
14781 case Type::TypeOfExpr:
14782 return QualType();
14783
14784 case Type::UnaryTransform: {
14785 const auto *UX = cast<UnaryTransformType>(X),
14786 *UY = cast<UnaryTransformType>(Y);
14787 UnaryTransformType::UTTKind KX = UX->getUTTKind();
14788 if (KX != UY->getUTTKind())
14789 return QualType();
14790 QualType BX = UX->getBaseType(), BY = UY->getBaseType();
14791 if (!Ctx.hasSameType(BX, BY))
14792 return QualType();
14793 // FIXME: It's inefficient to have to unify the base types.
14794 return Ctx.getUnaryTransformType(Ctx.getCommonSugaredType(BX, BY),
14795 Ctx.getQualifiedType(Underlying), KX);
14796 }
14797 case Type::Using: {
14798 const auto *UX = cast<UsingType>(X), *UY = cast<UsingType>(Y);
14799 const UsingShadowDecl *CD = ::getCommonDecl(UX->getDecl(), UY->getDecl());
14800 if (!CD)
14801 return QualType();
14802 return Ctx.getUsingType(::getCommonTypeKeyword(UX, UY, /*IsSame=*/false),
14803 ::getCommonQualifier(Ctx, UX, UY, /*IsSame=*/false),
14804 CD, Ctx.getQualifiedType(Underlying));
14805 }
14806 case Type::MemberPointer: {
14807 const auto *PX = cast<MemberPointerType>(X),
14808 *PY = cast<MemberPointerType>(Y);
14809 CXXRecordDecl *Cls = PX->getMostRecentCXXRecordDecl();
14810 assert(Cls == PY->getMostRecentCXXRecordDecl());
14811 return Ctx.getMemberPointerType(
14812 ::getCommonPointeeType(Ctx, PX, PY),
14813 ::getCommonQualifier(Ctx, PX, PY, /*IsSame=*/false), Cls);
14814 }
14815 case Type::CountAttributed: {
14816 const auto *DX = cast<CountAttributedType>(X),
14818 if (DX->isCountInBytes() != DY->isCountInBytes())
14819 return QualType();
14820 if (DX->isOrNull() != DY->isOrNull())
14821 return QualType();
14822 Expr *CEX = DX->getCountExpr();
14823 Expr *CEY = DY->getCountExpr();
14824 ArrayRef<clang::TypeCoupledDeclRefInfo> CDX = DX->getCoupledDecls();
14825 if (Ctx.hasSameExpr(CEX, CEY))
14826 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX,
14827 DX->isCountInBytes(), DX->isOrNull(),
14828 CDX);
14829 if (!CEX->isIntegerConstantExpr(Ctx) || !CEY->isIntegerConstantExpr(Ctx))
14830 return QualType();
14831 // Two declarations with the same integer constant may still differ in their
14832 // expression pointers, so we need to evaluate them.
14833 llvm::APSInt VX = *CEX->getIntegerConstantExpr(Ctx);
14834 llvm::APSInt VY = *CEY->getIntegerConstantExpr(Ctx);
14835 if (VX != VY)
14836 return QualType();
14837 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX,
14838 DX->isCountInBytes(), DX->isOrNull(),
14839 CDX);
14840 }
14841 case Type::PredefinedSugar:
14842 assert(cast<PredefinedSugarType>(X)->getKind() !=
14844 return QualType();
14845 }
14846 llvm_unreachable("Unhandled Type Class");
14847}
14848
14849static auto unwrapSugar(SplitQualType &T, Qualifiers &QTotal) {
14851 while (true) {
14852 QTotal.addConsistentQualifiers(T.Quals);
14854 if (NT == QualType(T.Ty, 0))
14855 break;
14856 R.push_back(T);
14857 T = NT.split();
14858 }
14859 return R;
14860}
14861
14863 bool Unqualified) const {
14864 assert(Unqualified ? hasSameUnqualifiedType(X, Y) : hasSameType(X, Y));
14865 if (X == Y)
14866 return X;
14867 if (!Unqualified) {
14868 if (X.isCanonical())
14869 return X;
14870 if (Y.isCanonical())
14871 return Y;
14872 }
14873
14874 SplitQualType SX = X.split(), SY = Y.split();
14875 Qualifiers QX, QY;
14876 // Desugar SX and SY, setting the sugar and qualifiers aside into Xs and Ys,
14877 // until we reach their underlying "canonical nodes". Note these are not
14878 // necessarily canonical types, as they may still have sugared properties.
14879 // QX and QY will store the sum of all qualifiers in Xs and Ys respectively.
14880 auto Xs = ::unwrapSugar(SX, QX), Ys = ::unwrapSugar(SY, QY);
14881
14882 // If this is an ArrayType, the element qualifiers are interchangeable with
14883 // the top level qualifiers.
14884 // * In case the canonical nodes are the same, the elements types are already
14885 // the same.
14886 // * Otherwise, the element types will be made the same, and any different
14887 // element qualifiers will be moved up to the top level qualifiers, per
14888 // 'getCommonArrayElementType'.
14889 // In both cases, this means there may be top level qualifiers which differ
14890 // between X and Y. If so, these differing qualifiers are redundant with the
14891 // element qualifiers, and can be removed without changing the canonical type.
14892 // The desired behaviour is the same as for the 'Unqualified' case here:
14893 // treat the redundant qualifiers as sugar, remove the ones which are not
14894 // common to both sides.
14895 bool KeepCommonQualifiers =
14897
14898 if (SX.Ty != SY.Ty) {
14899 // The canonical nodes differ. Build a common canonical node out of the two,
14900 // unifying their sugar. This may recurse back here.
14901 SX.Ty =
14902 ::getCommonNonSugarTypeNode(*this, SX.Ty, QX, SY.Ty, QY).getTypePtr();
14903 } else {
14904 // The canonical nodes were identical: We may have desugared too much.
14905 // Add any common sugar back in.
14906 while (!Xs.empty() && !Ys.empty() && Xs.back().Ty == Ys.back().Ty) {
14907 QX -= SX.Quals;
14908 QY -= SY.Quals;
14909 SX = Xs.pop_back_val();
14910 SY = Ys.pop_back_val();
14911 }
14912 }
14913 if (KeepCommonQualifiers)
14915 else
14916 assert(QX == QY);
14917
14918 // Even though the remaining sugar nodes in Xs and Ys differ, some may be
14919 // related. Walk up these nodes, unifying them and adding the result.
14920 while (!Xs.empty() && !Ys.empty()) {
14921 auto Underlying = SplitQualType(
14922 SX.Ty, Qualifiers::removeCommonQualifiers(SX.Quals, SY.Quals));
14923 SX = Xs.pop_back_val();
14924 SY = Ys.pop_back_val();
14925 SX.Ty = ::getCommonSugarTypeNode(*this, SX.Ty, SY.Ty, Underlying)
14927 // Stop at the first pair which is unrelated.
14928 if (!SX.Ty) {
14929 SX.Ty = Underlying.Ty;
14930 break;
14931 }
14932 QX -= Underlying.Quals;
14933 };
14934
14935 // Add back the missing accumulated qualifiers, which were stripped off
14936 // with the sugar nodes we could not unify.
14937 QualType R = getQualifiedType(SX.Ty, QX);
14938 assert(Unqualified ? hasSameUnqualifiedType(R, X) : hasSameType(R, X));
14939 return R;
14940}
14941
14943 assert(Ty->isFixedPointType());
14944
14946 return Ty;
14947
14948 switch (Ty->castAs<BuiltinType>()->getKind()) {
14949 default:
14950 llvm_unreachable("Not a saturated fixed point type!");
14951 case BuiltinType::SatShortAccum:
14952 return ShortAccumTy;
14953 case BuiltinType::SatAccum:
14954 return AccumTy;
14955 case BuiltinType::SatLongAccum:
14956 return LongAccumTy;
14957 case BuiltinType::SatUShortAccum:
14958 return UnsignedShortAccumTy;
14959 case BuiltinType::SatUAccum:
14960 return UnsignedAccumTy;
14961 case BuiltinType::SatULongAccum:
14962 return UnsignedLongAccumTy;
14963 case BuiltinType::SatShortFract:
14964 return ShortFractTy;
14965 case BuiltinType::SatFract:
14966 return FractTy;
14967 case BuiltinType::SatLongFract:
14968 return LongFractTy;
14969 case BuiltinType::SatUShortFract:
14970 return UnsignedShortFractTy;
14971 case BuiltinType::SatUFract:
14972 return UnsignedFractTy;
14973 case BuiltinType::SatULongFract:
14974 return UnsignedLongFractTy;
14975 }
14976}
14977
14979 assert(Ty->isFixedPointType());
14980
14981 if (Ty->isSaturatedFixedPointType()) return Ty;
14982
14983 switch (Ty->castAs<BuiltinType>()->getKind()) {
14984 default:
14985 llvm_unreachable("Not a fixed point type!");
14986 case BuiltinType::ShortAccum:
14987 return SatShortAccumTy;
14988 case BuiltinType::Accum:
14989 return SatAccumTy;
14990 case BuiltinType::LongAccum:
14991 return SatLongAccumTy;
14992 case BuiltinType::UShortAccum:
14994 case BuiltinType::UAccum:
14995 return SatUnsignedAccumTy;
14996 case BuiltinType::ULongAccum:
14998 case BuiltinType::ShortFract:
14999 return SatShortFractTy;
15000 case BuiltinType::Fract:
15001 return SatFractTy;
15002 case BuiltinType::LongFract:
15003 return SatLongFractTy;
15004 case BuiltinType::UShortFract:
15006 case BuiltinType::UFract:
15007 return SatUnsignedFractTy;
15008 case BuiltinType::ULongFract:
15010 }
15011}
15012
15014 if (LangOpts.OpenCL)
15016
15017 if (LangOpts.CUDA)
15019
15020 return getLangASFromTargetAS(AS);
15021}
15022
15023// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
15024// doesn't include ASTContext.h
15025template
15027 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
15029 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
15030 const clang::ASTContext &Ctx, Decl *Value);
15031
15033 assert(Ty->isFixedPointType());
15034
15035 const TargetInfo &Target = getTargetInfo();
15036 switch (Ty->castAs<BuiltinType>()->getKind()) {
15037 default:
15038 llvm_unreachable("Not a fixed point type!");
15039 case BuiltinType::ShortAccum:
15040 case BuiltinType::SatShortAccum:
15041 return Target.getShortAccumScale();
15042 case BuiltinType::Accum:
15043 case BuiltinType::SatAccum:
15044 return Target.getAccumScale();
15045 case BuiltinType::LongAccum:
15046 case BuiltinType::SatLongAccum:
15047 return Target.getLongAccumScale();
15048 case BuiltinType::UShortAccum:
15049 case BuiltinType::SatUShortAccum:
15050 return Target.getUnsignedShortAccumScale();
15051 case BuiltinType::UAccum:
15052 case BuiltinType::SatUAccum:
15053 return Target.getUnsignedAccumScale();
15054 case BuiltinType::ULongAccum:
15055 case BuiltinType::SatULongAccum:
15056 return Target.getUnsignedLongAccumScale();
15057 case BuiltinType::ShortFract:
15058 case BuiltinType::SatShortFract:
15059 return Target.getShortFractScale();
15060 case BuiltinType::Fract:
15061 case BuiltinType::SatFract:
15062 return Target.getFractScale();
15063 case BuiltinType::LongFract:
15064 case BuiltinType::SatLongFract:
15065 return Target.getLongFractScale();
15066 case BuiltinType::UShortFract:
15067 case BuiltinType::SatUShortFract:
15068 return Target.getUnsignedShortFractScale();
15069 case BuiltinType::UFract:
15070 case BuiltinType::SatUFract:
15071 return Target.getUnsignedFractScale();
15072 case BuiltinType::ULongFract:
15073 case BuiltinType::SatULongFract:
15074 return Target.getUnsignedLongFractScale();
15075 }
15076}
15077
15079 assert(Ty->isFixedPointType());
15080
15081 const TargetInfo &Target = getTargetInfo();
15082 switch (Ty->castAs<BuiltinType>()->getKind()) {
15083 default:
15084 llvm_unreachable("Not a fixed point type!");
15085 case BuiltinType::ShortAccum:
15086 case BuiltinType::SatShortAccum:
15087 return Target.getShortAccumIBits();
15088 case BuiltinType::Accum:
15089 case BuiltinType::SatAccum:
15090 return Target.getAccumIBits();
15091 case BuiltinType::LongAccum:
15092 case BuiltinType::SatLongAccum:
15093 return Target.getLongAccumIBits();
15094 case BuiltinType::UShortAccum:
15095 case BuiltinType::SatUShortAccum:
15096 return Target.getUnsignedShortAccumIBits();
15097 case BuiltinType::UAccum:
15098 case BuiltinType::SatUAccum:
15099 return Target.getUnsignedAccumIBits();
15100 case BuiltinType::ULongAccum:
15101 case BuiltinType::SatULongAccum:
15102 return Target.getUnsignedLongAccumIBits();
15103 case BuiltinType::ShortFract:
15104 case BuiltinType::SatShortFract:
15105 case BuiltinType::Fract:
15106 case BuiltinType::SatFract:
15107 case BuiltinType::LongFract:
15108 case BuiltinType::SatLongFract:
15109 case BuiltinType::UShortFract:
15110 case BuiltinType::SatUShortFract:
15111 case BuiltinType::UFract:
15112 case BuiltinType::SatUFract:
15113 case BuiltinType::ULongFract:
15114 case BuiltinType::SatULongFract:
15115 return 0;
15116 }
15117}
15118
15119llvm::FixedPointSemantics
15121 assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
15122 "Can only get the fixed point semantics for a "
15123 "fixed point or integer type.");
15124 if (Ty->isIntegerType())
15125 return llvm::FixedPointSemantics::GetIntegerSemantics(
15126 getIntWidth(Ty), Ty->isSignedIntegerType());
15127
15128 bool isSigned = Ty->isSignedFixedPointType();
15129 return llvm::FixedPointSemantics(
15130 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
15132 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
15133}
15134
15135llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
15136 assert(Ty->isFixedPointType());
15137 return llvm::APFixedPoint::getMax(getFixedPointSemantics(Ty));
15138}
15139
15140llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
15141 assert(Ty->isFixedPointType());
15142 return llvm::APFixedPoint::getMin(getFixedPointSemantics(Ty));
15143}
15144
15146 assert(Ty->isUnsignedFixedPointType() &&
15147 "Expected unsigned fixed point type");
15148
15149 switch (Ty->castAs<BuiltinType>()->getKind()) {
15150 case BuiltinType::UShortAccum:
15151 return ShortAccumTy;
15152 case BuiltinType::UAccum:
15153 return AccumTy;
15154 case BuiltinType::ULongAccum:
15155 return LongAccumTy;
15156 case BuiltinType::SatUShortAccum:
15157 return SatShortAccumTy;
15158 case BuiltinType::SatUAccum:
15159 return SatAccumTy;
15160 case BuiltinType::SatULongAccum:
15161 return SatLongAccumTy;
15162 case BuiltinType::UShortFract:
15163 return ShortFractTy;
15164 case BuiltinType::UFract:
15165 return FractTy;
15166 case BuiltinType::ULongFract:
15167 return LongFractTy;
15168 case BuiltinType::SatUShortFract:
15169 return SatShortFractTy;
15170 case BuiltinType::SatUFract:
15171 return SatFractTy;
15172 case BuiltinType::SatULongFract:
15173 return SatLongFractTy;
15174 default:
15175 llvm_unreachable("Unexpected unsigned fixed point type");
15176 }
15177}
15178
15179// Given a list of FMV features, return a concatenated list of the
15180// corresponding backend features (which may contain duplicates).
15181static std::vector<std::string> getFMVBackendFeaturesFor(
15182 const llvm::SmallVectorImpl<StringRef> &FMVFeatStrings) {
15183 std::vector<std::string> BackendFeats;
15184 llvm::AArch64::ExtensionSet FeatureBits;
15185 for (StringRef F : FMVFeatStrings)
15186 if (auto FMVExt = llvm::AArch64::parseFMVExtension(F))
15187 if (FMVExt->ID)
15188 FeatureBits.enable(*FMVExt->ID);
15189 FeatureBits.toLLVMFeatureList(BackendFeats);
15190 return BackendFeats;
15191}
15192
15193ParsedTargetAttr
15194ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const {
15195 assert(TD != nullptr);
15196 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(TD->getFeaturesStr());
15197
15198 llvm::erase_if(ParsedAttr.Features, [&](const std::string &Feat) {
15199 return !Target->isValidFeatureName(StringRef{Feat}.substr(1));
15200 });
15201 return ParsedAttr;
15202}
15203
15204void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
15205 const FunctionDecl *FD) const {
15206 if (FD)
15207 getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD));
15208 else
15209 Target->initFeatureMap(FeatureMap, getDiagnostics(),
15210 Target->getTargetOpts().CPU,
15211 Target->getTargetOpts().Features);
15212}
15213
15214// Fills in the supplied string map with the set of target features for the
15215// passed in function.
15216void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
15217 GlobalDecl GD) const {
15218 StringRef TargetCPU = Target->getTargetOpts().CPU;
15219 const FunctionDecl *FD = GD.getDecl()->getAsFunction();
15220 if (const auto *TD = FD->getAttr<TargetAttr>()) {
15222
15223 // Make a copy of the features as passed on the command line into the
15224 // beginning of the additional features from the function to override.
15225 // AArch64 handles command line option features in parseTargetAttr().
15226 if (!Target->getTriple().isAArch64())
15227 ParsedAttr.Features.insert(
15228 ParsedAttr.Features.begin(),
15229 Target->getTargetOpts().FeaturesAsWritten.begin(),
15230 Target->getTargetOpts().FeaturesAsWritten.end());
15231
15232 if (ParsedAttr.CPU != "" && Target->isValidCPUName(ParsedAttr.CPU))
15233 TargetCPU = ParsedAttr.CPU;
15234
15235 // Now populate the feature map, first with the TargetCPU which is either
15236 // the default or a new one from the target attribute string. Then we'll use
15237 // the passed in features (FeaturesAsWritten) along with the new ones from
15238 // the attribute.
15239 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU,
15240 ParsedAttr.Features);
15241 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
15243 Target->getCPUSpecificCPUDispatchFeatures(
15244 SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp);
15245 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
15246 Features.insert(Features.begin(),
15247 Target->getTargetOpts().FeaturesAsWritten.begin(),
15248 Target->getTargetOpts().FeaturesAsWritten.end());
15249 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15250 } else if (const auto *TC = FD->getAttr<TargetClonesAttr>()) {
15251 if (Target->getTriple().isAArch64()) {
15253 TC->getFeatures(Feats, GD.getMultiVersionIndex());
15254 std::vector<std::string> Features = getFMVBackendFeaturesFor(Feats);
15255 Features.insert(Features.begin(),
15256 Target->getTargetOpts().FeaturesAsWritten.begin(),
15257 Target->getTargetOpts().FeaturesAsWritten.end());
15258 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15259 } else if (Target->getTriple().isRISCV()) {
15260 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
15261 std::vector<std::string> Features;
15262 if (VersionStr != "default") {
15263 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(VersionStr);
15264 Features.insert(Features.begin(), ParsedAttr.Features.begin(),
15265 ParsedAttr.Features.end());
15266 }
15267 Features.insert(Features.begin(),
15268 Target->getTargetOpts().FeaturesAsWritten.begin(),
15269 Target->getTargetOpts().FeaturesAsWritten.end());
15270 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15271 } else if (Target->getTriple().isOSAIX()) {
15272 std::vector<std::string> Features;
15273 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
15274 if (VersionStr.starts_with("cpu="))
15275 TargetCPU = VersionStr.drop_front(sizeof("cpu=") - 1);
15276 else
15277 assert(VersionStr == "default");
15278 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15279 } else {
15280 std::vector<std::string> Features;
15281 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
15282 if (VersionStr.starts_with("arch="))
15283 TargetCPU = VersionStr.drop_front(sizeof("arch=") - 1);
15284 else if (VersionStr != "default")
15285 Features.push_back((StringRef{"+"} + VersionStr).str());
15286 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15287 }
15288 } else if (const auto *TV = FD->getAttr<TargetVersionAttr>()) {
15289 std::vector<std::string> Features;
15290 if (Target->getTriple().isRISCV()) {
15291 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(TV->getName());
15292 Features.insert(Features.begin(), ParsedAttr.Features.begin(),
15293 ParsedAttr.Features.end());
15294 } else {
15295 assert(Target->getTriple().isAArch64());
15297 TV->getFeatures(Feats);
15298 Features = getFMVBackendFeaturesFor(Feats);
15299 }
15300 Features.insert(Features.begin(),
15301 Target->getTargetOpts().FeaturesAsWritten.begin(),
15302 Target->getTargetOpts().FeaturesAsWritten.end());
15303 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15304 } else {
15305 FeatureMap = Target->getTargetOpts().FeatureMap;
15306 }
15307}
15308
15310 CanQualType KernelNameType,
15311 const FunctionDecl *FD) {
15312 // Host and device compilation may use different ABIs and different ABIs
15313 // may allocate name mangling discriminators differently. A discriminator
15314 // override is used to ensure consistent discriminator allocation across
15315 // host and device compilation.
15316 auto DeviceDiscriminatorOverrider =
15317 [](ASTContext &Ctx, const NamedDecl *ND) -> UnsignedOrNone {
15318 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
15319 if (RD->isLambda())
15320 return RD->getDeviceLambdaManglingNumber();
15321 return std::nullopt;
15322 };
15323 std::unique_ptr<MangleContext> MC{ItaniumMangleContext::create(
15324 Context, Context.getDiagnostics(), DeviceDiscriminatorOverrider)};
15325
15326 // Construct a mangled name for the SYCL kernel caller offload entry point.
15327 // FIXME: The Itanium typeinfo mangling (_ZTS<type>) is currently used to
15328 // name the SYCL kernel caller offload entry point function. This mangling
15329 // does not suffice to clearly identify symbols that correspond to SYCL
15330 // kernel caller functions, nor is this mangling natural for targets that
15331 // use a non-Itanium ABI.
15332 std::string Buffer;
15333 Buffer.reserve(128);
15334 llvm::raw_string_ostream Out(Buffer);
15335 MC->mangleCanonicalTypeName(KernelNameType, Out);
15336 std::string KernelName = Out.str();
15337
15338 return {KernelNameType, FD, KernelName};
15339}
15340
15342 // If the function declaration to register is invalid or dependent, the
15343 // registration attempt is ignored.
15344 if (FD->isInvalidDecl() || FD->isTemplated())
15345 return;
15346
15347 const auto *SKEPAttr = FD->getAttr<SYCLKernelEntryPointAttr>();
15348 assert(SKEPAttr && "Missing sycl_kernel_entry_point attribute");
15349
15350 // Be tolerant of multiple registration attempts so long as each attempt
15351 // is for the same entity. Callers are obligated to detect and diagnose
15352 // conflicting kernel names prior to calling this function.
15353 CanQualType KernelNameType = getCanonicalType(SKEPAttr->getKernelName());
15354 auto IT = SYCLKernels.find(KernelNameType);
15355 assert((IT == SYCLKernels.end() ||
15356 declaresSameEntity(FD, IT->second.getKernelEntryPointDecl())) &&
15357 "SYCL kernel name conflict");
15358 (void)IT;
15359 SYCLKernels.insert(std::make_pair(
15360 KernelNameType, BuildSYCLKernelInfo(*this, KernelNameType, FD)));
15361}
15362
15364 CanQualType KernelNameType = getCanonicalType(T);
15365 return SYCLKernels.at(KernelNameType);
15366}
15367
15369 CanQualType KernelNameType = getCanonicalType(T);
15370 auto IT = SYCLKernels.find(KernelNameType);
15371 if (IT != SYCLKernels.end())
15372 return &IT->second;
15373 return nullptr;
15374}
15375
15377 OMPTraitInfoVector.emplace_back(new OMPTraitInfo());
15378 return *OMPTraitInfoVector.back();
15379}
15380
15383 const ASTContext::SectionInfo &Section) {
15384 if (Section.Decl)
15385 return DB << Section.Decl;
15386 return DB << "a prior #pragma section";
15387}
15388
15389bool ASTContext::mayExternalize(const Decl *D) const {
15390 bool IsInternalVar =
15391 isa<VarDecl>(D) &&
15393 bool IsExplicitDeviceVar = (D->hasAttr<CUDADeviceAttr>() &&
15394 !D->getAttr<CUDADeviceAttr>()->isImplicit()) ||
15395 (D->hasAttr<CUDAConstantAttr>() &&
15396 !D->getAttr<CUDAConstantAttr>()->isImplicit());
15397 // CUDA/HIP: managed variables need to be externalized since it is
15398 // a declaration in IR, therefore cannot have internal linkage. Kernels in
15399 // anonymous name space needs to be externalized to avoid duplicate symbols.
15400 return (IsInternalVar &&
15401 (D->hasAttr<HIPManagedAttr>() || IsExplicitDeviceVar)) ||
15402 (D->hasAttr<CUDAGlobalAttr>() &&
15404 GVA_Internal);
15405}
15406
15408 return mayExternalize(D) &&
15409 (D->hasAttr<HIPManagedAttr>() || D->hasAttr<CUDAGlobalAttr>() ||
15411}
15412
15413StringRef ASTContext::getCUIDHash() const {
15414 if (!CUIDHash.empty())
15415 return CUIDHash;
15416 if (LangOpts.CUID.empty())
15417 return StringRef();
15418 CUIDHash = llvm::utohexstr(llvm::MD5Hash(LangOpts.CUID), /*LowerCase=*/true);
15419 return CUIDHash;
15420}
15421
15422const CXXRecordDecl *
15424 assert(ThisClass);
15425 assert(ThisClass->isPolymorphic());
15426 const CXXRecordDecl *PrimaryBase = ThisClass;
15427 while (1) {
15428 assert(PrimaryBase);
15429 assert(PrimaryBase->isPolymorphic());
15430 auto &Layout = getASTRecordLayout(PrimaryBase);
15431 auto Base = Layout.getPrimaryBase();
15432 if (!Base || Base == PrimaryBase || !Base->isPolymorphic())
15433 break;
15434 PrimaryBase = Base;
15435 }
15436 return PrimaryBase;
15437}
15438
15440 StringRef MangledName) {
15441 auto *Method = cast<CXXMethodDecl>(VirtualMethodDecl.getDecl());
15442 assert(Method->isVirtual());
15443 bool DefaultIncludesPointerAuth =
15444 LangOpts.PointerAuthCalls || LangOpts.PointerAuthIntrinsics;
15445
15446 if (!DefaultIncludesPointerAuth)
15447 return true;
15448
15449 auto Existing = ThunksToBeAbbreviated.find(VirtualMethodDecl);
15450 if (Existing != ThunksToBeAbbreviated.end())
15451 return Existing->second.contains(MangledName.str());
15452
15453 std::unique_ptr<MangleContext> Mangler(createMangleContext());
15454 llvm::StringMap<llvm::SmallVector<std::string, 2>> Thunks;
15455 auto VtableContext = getVTableContext();
15456 if (const auto *ThunkInfos = VtableContext->getThunkInfo(VirtualMethodDecl)) {
15457 auto *Destructor = dyn_cast<CXXDestructorDecl>(Method);
15458 for (const auto &Thunk : *ThunkInfos) {
15459 SmallString<256> ElidedName;
15460 llvm::raw_svector_ostream ElidedNameStream(ElidedName);
15461 if (Destructor)
15462 Mangler->mangleCXXDtorThunk(Destructor, VirtualMethodDecl.getDtorType(),
15463 Thunk, /* elideOverrideInfo */ true,
15464 ElidedNameStream);
15465 else
15466 Mangler->mangleThunk(Method, Thunk, /* elideOverrideInfo */ true,
15467 ElidedNameStream);
15468 SmallString<256> MangledName;
15469 llvm::raw_svector_ostream mangledNameStream(MangledName);
15470 if (Destructor)
15471 Mangler->mangleCXXDtorThunk(Destructor, VirtualMethodDecl.getDtorType(),
15472 Thunk, /* elideOverrideInfo */ false,
15473 mangledNameStream);
15474 else
15475 Mangler->mangleThunk(Method, Thunk, /* elideOverrideInfo */ false,
15476 mangledNameStream);
15477
15478 Thunks[ElidedName].push_back(std::string(MangledName));
15479 }
15480 }
15481 llvm::StringSet<> SimplifiedThunkNames;
15482 for (auto &ThunkList : Thunks) {
15483 llvm::sort(ThunkList.second);
15484 SimplifiedThunkNames.insert(ThunkList.second[0]);
15485 }
15486 bool Result = SimplifiedThunkNames.contains(MangledName);
15487 ThunksToBeAbbreviated[VirtualMethodDecl] = std::move(SimplifiedThunkNames);
15488 return Result;
15489}
15490
15492 // Check for trivially-destructible here because non-trivially-destructible
15493 // types will always cause the type and any types derived from it to be
15494 // considered non-trivially-copyable. The same cannot be said for
15495 // trivially-copyable because deleting special members of a type derived from
15496 // a non-trivially-copyable type can cause the derived type to be considered
15497 // trivially copyable.
15498 if (getLangOpts().PointerFieldProtectionTagged)
15499 return !isa<CXXRecordDecl>(RD) ||
15500 cast<CXXRecordDecl>(RD)->hasTrivialDestructor();
15501 return true;
15502}
15503
15504static void findPFPFields(const ASTContext &Ctx, QualType Ty, CharUnits Offset,
15505 std::vector<PFPField> &Fields, bool IncludeVBases) {
15506 if (auto *AT = Ctx.getAsConstantArrayType(Ty)) {
15507 if (auto *ElemDecl = AT->getElementType()->getAsCXXRecordDecl()) {
15508 const ASTRecordLayout &ElemRL = Ctx.getASTRecordLayout(ElemDecl);
15509 for (unsigned i = 0; i != AT->getSize(); ++i)
15510 findPFPFields(Ctx, AT->getElementType(), Offset + i * ElemRL.getSize(),
15511 Fields, true);
15512 }
15513 }
15514 auto *Decl = Ty->getAsCXXRecordDecl();
15515 // isPFPType() is inherited from bases and members (including via arrays), so
15516 // we can early exit if it is false. Unions are excluded per the API
15517 // documentation.
15518 if (!Decl || !Decl->isPFPType() || Decl->isUnion())
15519 return;
15520 const ASTRecordLayout &RL = Ctx.getASTRecordLayout(Decl);
15521 for (FieldDecl *Field : Decl->fields()) {
15522 CharUnits FieldOffset =
15523 Offset +
15524 Ctx.toCharUnitsFromBits(RL.getFieldOffset(Field->getFieldIndex()));
15525 if (Ctx.isPFPField(Field))
15526 Fields.push_back({FieldOffset, Field});
15527 findPFPFields(Ctx, Field->getType(), FieldOffset, Fields,
15528 /*IncludeVBases=*/true);
15529 }
15530 // Pass false for IncludeVBases below because vbases are only included in
15531 // layout for top-level types, i.e. not bases or vbases.
15532 for (CXXBaseSpecifier &Base : Decl->bases()) {
15533 if (Base.isVirtual())
15534 continue;
15535 CharUnits BaseOffset =
15536 Offset + RL.getBaseClassOffset(Base.getType()->getAsCXXRecordDecl());
15537 findPFPFields(Ctx, Base.getType(), BaseOffset, Fields,
15538 /*IncludeVBases=*/false);
15539 }
15540 if (IncludeVBases) {
15541 for (CXXBaseSpecifier &Base : Decl->vbases()) {
15542 CharUnits BaseOffset =
15543 Offset + RL.getVBaseClassOffset(Base.getType()->getAsCXXRecordDecl());
15544 findPFPFields(Ctx, Base.getType(), BaseOffset, Fields,
15545 /*IncludeVBases=*/false);
15546 }
15547 }
15548}
15549
15550std::vector<PFPField> ASTContext::findPFPFields(QualType Ty) const {
15551 std::vector<PFPField> PFPFields;
15552 ::findPFPFields(*this, Ty, CharUnits::Zero(), PFPFields, true);
15553 return PFPFields;
15554}
15555
15557 return !findPFPFields(Ty).empty();
15558}
15559
15560bool ASTContext::isPFPField(const FieldDecl *FD) const {
15561 if (auto *RD = dyn_cast<CXXRecordDecl>(FD->getParent()))
15562 return RD->isPFPType() && FD->getType()->isPointerType() &&
15563 !FD->hasAttr<NoFieldProtectionAttr>();
15564 return false;
15565}
15566
15568 auto *FD = dyn_cast<FieldDecl>(VD);
15569 if (!FD)
15570 FD = cast<FieldDecl>(cast<IndirectFieldDecl>(VD)->chain().back());
15571 if (isPFPField(FD))
15573}
15574
15576 if (E->getNumComponents() == 0)
15577 return;
15578 OffsetOfNode Comp = E->getComponent(E->getNumComponents() - 1);
15579 if (Comp.getKind() != OffsetOfNode::Field)
15580 return;
15581 if (FieldDecl *FD = Comp.getField(); isPFPField(FD))
15583}
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 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 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 bool matchesPostDecrInWhile(const UnaryOperator *UO, ASTContext &Ctx)
For the purposes of overflow pattern exclusion, does this match the while(i–) pattern?
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 QualType getCommonTypeWithQualifierLifting(const ASTContext &Ctx, QualType X, QualType Y, Qualifiers &QX, Qualifiers &QY)
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:475
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:2848
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::Target Target
Definition MachO.h:51
llvm::MachO::Record Record
Definition MachO.h:31
static bool hasFeature(StringRef Feature, const LangOptions &LangOpts, const TargetInfo &Target)
Determine whether a translation unit built using the current language options has the given feature.
Definition Module.cpp:95
Defines the clang::Module class, which describes a module in the source code.
static StringRef getTriple(const Command &Job)
Defines types useful for describing an Objective-C runtime.
#define SM(sm)
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a kind
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:1105
const ValueDecl * getMemberPointerDecl() const
Definition APValue.cpp:1098
ArrayRef< const CXXRecordDecl * > getMemberPointerPath() const
Definition APValue.cpp:1112
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:227
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.
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.
bool dtorHasOperatorDelete(const CXXDestructorDecl *Dtor, OperatorDeleteKind K) const
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.
bool isPFPField(const FieldDecl *Field) const
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.
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
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:809
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.
const TemplateArgument * getDefaultTemplateArgumentOrNone(const NamedDecl *P) const
Return the default argument of a template parameter, if one exists.
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:810
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,...
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 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)
void setClassMaybeNeedsVectorDeletingDestructor(const CXXRecordDecl *RD)
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
std::optional< QualType > tryMergeOverflowBehaviorTypes(QualType LHS, QualType RHS, bool OfBlockPointer, bool Unqualified, bool BlockReturnType, bool IsConditionalOperator)
Attempts to merge two types that may be OverflowBehaviorTypes.
CanQualType WideCharTy
CanQualType OMPIteratorTy
IdentifierTable & Idents
Definition ASTContext.h:805
Builtin::Context & BuiltinInfo
Definition ASTContext.h:807
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:959
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:806
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:994
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 getAutoType(DeducedKind DK, QualType DeducedAsType, AutoTypeKeyword Keyword, TemplateDecl *TypeConstraintConcept=nullptr, ArrayRef< TemplateArgument > TypeConstraintArgs={}) const
C++11 deduced auto type.
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
llvm::SetVector< const VarDecl * > CUDADeviceVarODRUsedByHost
Keep track of CUDA/HIP device-side variables ODR-used by host code.
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
const TargetInfo * getAuxTargetInfo() const
Definition ASTContext.h:925
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:583
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:808
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 arePFPFieldsTriviallyCopyable(const RecordDecl *RD) const
Returns whether this record's PFP fields (if any) are trivially copyable (i.e.
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:997
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
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:228
void PrintStats() const
MangleContext * cudaNVInitDeviceMC()
unsigned getAlignOfGlobalVar(QualType T, const VarDecl *VD) const
Return the alignment in bits that should be given to a global variable with type T.
bool areCompatibleOverflowBehaviorTypes(QualType LHS, QualType RHS)
Return true if two OverflowBehaviorTypes are compatible for assignment.
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:811
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.
interp::Context & getInterpContext() const
Returns the clang bytecode interpreter context.
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.
bool hasPFPFields(QualType Ty) const
const clang::PrintingPolicy & getPrintingPolicy() const
Definition ASTContext.h:858
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:575
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...
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.
CanQualType OCLSamplerTy
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:879
ArrayRef< ExplicitInstantiationDecl * > getExplicitInstantiationDecls(const NamedDecl *Spec) const
Get all ExplicitInstantiationDecls for a given specialization.
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
FunctionDecl * getOperatorDeleteForVDtor(const CXXDestructorDecl *Dtor, OperatorDeleteKind K) const
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 ...
static bool hasSameType(QualType T1, QualType T2)
Determine whether the given types T1 and T2 are equivalent.
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 classMaybeNeedsVectorDeletingDestructor(const CXXRecordDecl *RD)
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
CanQualType Char32Ty
void recordOffsetOfEvaluation(const OffsetOfExpr *E)
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:924
void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl)
CanQualType OCLQueueTy
CanQualType LongFractTy
OBTAssignResult checkOBTAssignmentCompatibility(QualType LHS, QualType RHS)
Check overflow behavior type compatibility for assignments.
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.
void addExplicitInstantiationDecl(const NamedDecl *Spec, ExplicitInstantiationDecl *EID)
Add an ExplicitInstantiationDecl for a given specialization.
QualType getOverflowBehaviorType(const OverflowBehaviorAttr *Attr, QualType Wrapped) const
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
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.
uint64_t getArrayInitLoopExprElementCount(const ArrayInitLoopExpr *AILE) const
Return number of elements initialized in an ArrayInitLoopExpr.
unsigned getTargetAddressSpace(LangAS AS) const
std::vector< PFPField > findPFPFields(QualType Ty) const
Returns a list of PFP fields for the given type, including subfields in bases or other fields,...
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.
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
static bool hasSameUnqualifiedType(QualType T1, QualType T2)
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
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...
void addOperatorDeleteForVDtor(const CXXDestructorDecl *Dtor, FunctionDecl *OperatorDelete, OperatorDeleteKind K) const
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.
llvm::SetVector< const FieldDecl * > PFPFieldsWithEvaluatedOffset
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
bool isUnaryOverflowPatternExcluded(const UnaryOperator *UO)
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.
QualType getDeducedTemplateSpecializationType(DeducedKind DK, QualType DeducedAsType, ElaboratedTypeKeyword Keyword, TemplateName Template) const
C++17 deduced class template specialization type.
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)
void recordMemberDataPointerEvaluation(const ValueDecl *VD)
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:3544
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3565
Represents a loop initializing the elements of an array.
Definition Expr.h:5969
llvm::APInt getArraySize() const
Definition Expr.h:5991
Expr * getSubExpr() const
Get the initializer to use for each array element.
Definition Expr.h:5989
Represents a constant array type that does not decay to a pointer when used as a function parameter.
Definition TypeBase.h:3947
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3777
ArraySizeModifier getSizeModifier() const
Definition TypeBase.h:3791
Qualifiers getIndexTypeQualifiers() const
Definition TypeBase.h:3795
QualType getElementType() const
Definition TypeBase.h:3789
unsigned getIndexTypeCVRQualifiers() const
Definition TypeBase.h:3799
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:6929
Expr * getPtr() const
Definition Expr.h:6960
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:8240
Attr - This represents one attribute.
Definition Attr.h:46
A fixed int type of a specified bitwidth.
Definition TypeBase.h:8288
void Profile(llvm::FoldingSetNodeID &ID) const
Definition TypeBase.h:8305
unsigned getNumBits() const
Definition TypeBase.h:8300
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition Decl.h:4690
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition Expr.h:6673
Pointer to a block type.
Definition TypeBase.h:3597
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3614
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:3219
Kind getKind() const
Definition TypeBase.h:3267
Holds information about both target-independent and target-specific builtins, allowing easy queries b...
Definition Builtins.h:235
Implements C++ ABI-specific semantic analysis functions.
Definition CXXABI.h:29
virtual ~CXXABI()
Represents a base class of a C++ class.
Definition DeclCXX.h:146
Represents a C++ constructor within a class.
Definition DeclCXX.h:2620
Represents a C++ destructor within a class.
Definition DeclCXX.h:2882
CXXDestructorDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2930
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2132
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2241
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
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3330
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3345
bool hasExplicitTemplateArgs() const
Whether or not template arguments were explicitly specified in the concept reference (they might not ...
Definition ASTConcept.h:209
const ASTTemplateArgumentListInfo * getTemplateArgsAsWritten() const
Definition ASTConcept.h:203
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3815
const Expr * getSizeExpr() const
Return a pointer to the size expression.
Definition TypeBase.h:3911
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3871
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition TypeBase.h:3930
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3891
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4442
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition TypeBase.h:4461
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:4507
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition TypeBase.h:4458
Represents a sugar type with __counted_by or __sized_by annotations, including their _or_null variant...
Definition TypeBase.h:3491
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3527
Represents a pointer type decayed from an array or function type.
Definition TypeBase.h:3580
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1462
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2122
bool isFileContext() const
Definition DeclBase.h:2193
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition DeclBase.h:2138
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:2115
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1273
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:341
bool isModuleLocal() const
Whether this declaration was a local declaration to a C++20 named module.
T * getAttr() const
Definition DeclBase.h:581
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:547
void addAttr(Attr *A)
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:601
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl,...
Definition DeclBase.cpp:561
bool isUnconditionallyVisible() const
Determine whether this declaration is definitely visible to name lookup, independent of whether the o...
Definition DeclBase.h:867
static Decl * castFromDeclContext(const DeclContext *)
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition DeclBase.cpp:308
bool isCanonicalDecl() const
Whether this particular Decl is a canonical one.
Definition DeclBase.h:997
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition DeclBase.h:850
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition DeclBase.cpp:273
ObjCDeclQualifier
ObjCDeclQualifier - 'Qualifiers' written next to the return and parameter types in method declaration...
Definition DeclBase.h:198
bool isInvalidDecl() const
Definition DeclBase.h:596
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:567
SourceLocation getLocation() const
Definition DeclBase.h:447
void setImplicit(bool I=true)
Definition DeclBase.h:602
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition DeclBase.h:1062
DeclContext * getDeclContext()
Definition DeclBase.h:456
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:439
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition DeclBase.cpp:382
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:931
bool hasAttr() const
Definition DeclBase.h:585
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:991
Kind getKind() const
Definition DeclBase.h:450
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:780
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:809
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:4116
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4138
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:8333
Represents an array type in C++ whose size is a value-dependent expression.
Definition TypeBase.h:4066
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4095
Represents an extended vector type where either the type or size is dependent.
Definition TypeBase.h:4156
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4181
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition TypeBase.h:4528
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4548
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:6307
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:6312
Represents a vector type where either the type or size is dependent.
Definition TypeBase.h:4282
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4307
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:233
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
A dynamically typed AST node container.
Represents an enum.
Definition Decl.h:4029
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition Decl.h:4247
bool isComplete() const
Returns true if this can be considered a complete type.
Definition Decl.h:4261
EnumDecl * getDefinitionOrSelf() const
Definition Decl.h:4145
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4202
Represents an explicit instantiation of a template entity in source code.
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:3095
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:447
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:4229
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:834
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:3070
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:4068
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:437
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:1728
void Profile(llvm::FoldingSetNodeID &ID) const
Definition TypeBase.h:1775
ExtVectorType - Extended vector type.
Definition TypeBase.h:4322
Declaration context for names declared as extern "C" in C++.
Definition Decl.h:247
static ExternCContextDecl * Create(const ASTContext &C, TranslationUnitDecl *TU)
Definition Decl.cpp:5543
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:3178
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3281
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition Decl.cpp:4747
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition Decl.h:3263
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3414
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:4695
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:2018
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition Decl.h:2707
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3757
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition Decl.h:2939
bool isMSExternInline() const
The combination of the extern and inline keywords under MSVC forces the function to be required.
Definition Decl.cpp:3886
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3742
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:4412
bool isUserProvided() const
True if this method is user-declared and was not deleted or defaulted on its first declaration.
Definition Decl.h:2428
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:4073
FunctionDecl * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
SmallVector< Conflict > Conflicts
Definition TypeBase.h:5330
static FunctionEffectSet getIntersection(FunctionEffectsRef LHS, FunctionEffectsRef RHS)
Definition Type.cpp:5795
static FunctionEffectSet getUnion(FunctionEffectsRef LHS, FunctionEffectsRef RHS, Conflicts &Errs)
Definition Type.cpp:5833
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5162
ArrayRef< EffectConditionExpr > conditions() const
Definition TypeBase.h:5196
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition TypeBase.h:4940
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:4956
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5362
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition TypeBase.h:5866
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition TypeBase.h:5669
unsigned getNumParams() const
Definition TypeBase.h:5640
QualType getParamType(unsigned i) const
Definition TypeBase.h:5642
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition Type.cpp:4078
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition TypeBase.h:5675
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5766
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5651
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5647
ArrayRef< ExtParameterInfo > getExtParameterInfos() const
Definition TypeBase.h:5835
bool hasExtParameterInfos() const
Is there any interesting extra information for any of the parameters of this function type?
Definition TypeBase.h:5831
Declaration of a template function.
A class which abstracts out some details necessary for making a call.
Definition TypeBase.h:4669
CallingConv getCC() const
Definition TypeBase.h:4728
unsigned getRegParm() const
Definition TypeBase.h:4721
bool getNoCallerSavedRegs() const
Definition TypeBase.h:4717
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4740
Interesting information about a specific parameter that can't simply be reflected in parameter's type...
Definition TypeBase.h:4584
ExtParameterInfo withIsNoEscape(bool NoEscape) const
Definition TypeBase.h:4624
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4558
ExtInfo getExtInfo() const
Definition TypeBase.h:4914
QualType getReturnType() const
Definition TypeBase.h:4898
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:5071
Represents a C array with an unspecified size.
Definition TypeBase.h:3964
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3981
static ItaniumMangleContext * create(ASTContext &Context, DiagnosticsEngine &Diags, bool IsAux=false)
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3672
@ 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.
@ PostDecrInWhile
while (count–)
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
bool isOverflowPatternExcluded(OverflowPatternExclusionKind Kind) const
A global _GUID constant.
Definition DeclCXX.h:4403
static void Profile(llvm::FoldingSetNodeID &ID, Parts P)
Definition DeclCXX.h:4440
MSGuidDeclParts Parts
Definition DeclCXX.h:4405
Sugar type that represents a type that was qualified by a qualifier written as a macro invocation.
Definition TypeBase.h:6241
MangleContext - Context for tracking state which persists across multiple calls to the C++ name mangl...
Definition Mangle.h:56
Keeps track of the mangled names of lambda expressions and block literals within a particular context...
static bool isValidElementType(QualType T, const LangOptions &LangOpts)
Valid elements types are the following:
Definition TypeBase.h:4413
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition TypeBase.h:4406
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3708
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3751
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:301
bool isNamedModule() const
Does this Module is a named module of a standard named module?
Definition Module.h:384
This represents a decl that may have a name.
Definition Decl.h:274
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:487
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
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:340
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:317
bool isExternallyVisible() const
Definition Decl.h:433
Represent a C++ namespace.
Definition Decl.h:592
static NamespaceDecl * Create(ASTContext &C, DeclContext *DC, bool Inline, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, NamespaceDecl *PrevDecl, bool Nested)
Definition DeclCXX.cpp:3366
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
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)
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:7998
ObjCInterfaceDecl * getDecl() const
Get the declaration of this interface.
Definition Type.cpp:988
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:8054
bool isObjCQualifiedClassType() const
True if this is equivalent to 'Class.
Definition TypeBase.h:8135
const ObjCObjectPointerType * stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const
Strip off the Objective-C "kindof" type and (with it) any protocol qualifiers.
Definition Type.cpp:995
bool isObjCQualifiedIdType() const
True if this is equivalent to 'id.
Definition TypeBase.h:8129
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:8211
const ObjCObjectType * getObjectType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:8091
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition TypeBase.h:8112
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:8066
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition TypeBase.h:8106
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition Type.cpp:1889
qual_range quals() const
Definition TypeBase.h:8173
bool isObjCClassType() const
True if this is equivalent to the 'Class' type, i.e.
Definition TypeBase.h:8118
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
OffsetOfExpr - [C99 7.17] - This represents an expression of the form offsetof(record-type,...
Definition Expr.h:2530
const OffsetOfNode & getComponent(unsigned Idx) const
Definition Expr.h:2577
unsigned getNumComponents() const
Definition Expr.h:2585
Helper class for OffsetOfExpr.
Definition Expr.h:2424
@ Field
A field.
Definition Expr.h:2431
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:4363
Sugar for parentheses used when specifying types.
Definition TypeBase.h:3357
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3371
void clear()
Clear parent maps.
DynTypedNodeList getParents(const NodeT &Node)
Returns the parents of the given node (within the traversal scope).
Represents a parameter to a function.
Definition Decl.h:1808
ObjCDeclQualifier getObjCDeclQualifier() const
Definition Decl.h:1872
QualType getOriginalType() const
Definition Decl.cpp:2961
ParsedAttr - Represents a syntactic attribute.
Definition ParsedAttr.h:119
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:8271
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:3383
QualType getPointeeType() const
Definition TypeBase.h:3393
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3398
PredefinedSugarKind Kind
Definition TypeBase.h:8347
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:1468
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8520
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition Type.cpp:2962
Qualifiers::GC getObjCGCAttr() const
Returns gc attribute of this type.
Definition TypeBase.h:8567
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8525
QualType getDesugaredType(const ASTContext &Context) const
Return the specified type with any "sugar" removed from the type.
Definition TypeBase.h:1307
QualType withConst() const
Definition TypeBase.h:1170
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:8436
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8562
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8476
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1449
QualType getCanonicalType() const
Definition TypeBase.h:8488
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8530
SplitQualType split() const
Divides a QualType into its unqualified type and a set of local qualifiers.
Definition TypeBase.h:8457
QualType getNonPackExpansionType() const
Remove an outer pack expansion type (if any) from this type.
Definition Type.cpp:3671
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8509
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition TypeBase.h:1556
bool isCanonical() const
Definition TypeBase.h:8493
const Type * getTypePtrOrNull() const
Definition TypeBase.h:8440
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1343
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:3105
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition TypeBase.h:8468
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:8376
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition TypeBase.h:8383
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:3690
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:4343
bool isLambda() const
Determine whether this record is a class describing a lambda function object.
Definition Decl.cpp:5241
bool hasFlexibleArrayMember() const
Definition Decl.h:4376
field_range fields() const
Definition Decl.h:4546
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition Decl.cpp:5227
RecordDecl * getMostRecentDecl()
Definition Decl.h:4369
virtual void completeDefinition()
Note that the definition of this type is now complete.
Definition Decl.cpp:5286
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition Decl.h:4527
bool field_empty() const
Definition Decl.h:4554
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:3628
QualType getPointeeType() const
Definition TypeBase.h:3646
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3654
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:1802
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:1188
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:3735
TagTypeKind TagKind
Definition Decl.h:3740
TypedefNameDecl * getTypedefNameForAnonDecl() const
Definition Decl.h:3972
void startDefinition()
Starts the definition of this tag declaration.
Definition Decl.cpp:4901
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:4894
bool isUnion() const
Definition Decl.h:3946
TagKind getTagKind() const
Definition Decl.h:3935
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:227
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:859
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:752
BuiltinVaListKind
The different kinds of __builtin_va_list types defined by the target implementation.
Definition TargetInfo.h:334
@ AArch64ABIBuiltinVaList
__builtin_va_list as defined by the AArch64 ABI http://infocenter.arm.com/help/topic/com....
Definition TargetInfo.h:343
@ PowerABIBuiltinVaList
__builtin_va_list as defined by the Power ABI: https://www.power.org /resources/downloads/Power-Arch-...
Definition TargetInfo.h:348
@ AAPCSABIBuiltinVaList
__builtin_va_list as defined by ARM AAPCS ABI http://infocenter.arm.com
Definition TargetInfo.h:357
@ CharPtrBuiltinVaList
typedef char* __builtin_va_list;
Definition TargetInfo.h:336
@ VoidPtrBuiltinVaList
typedef void* __builtin_va_list;
Definition TargetInfo.h:339
@ X86_64ABIBuiltinVaList
__builtin_va_list as defined by the x86-64 ABI: http://refspecs.linuxbase.org/elf/x86_64-abi-0....
Definition TargetInfo.h:352
virtual uint64_t getNullPointerValue(LangAS AddrSpace) const
Get integer value for null pointer.
Definition TargetInfo.h:506
static bool isTypeSigned(IntType T)
Returns true if the type is signed; false otherwise.
IntType getPtrDiffType(LangAS AddrSpace) const
Definition TargetInfo.h:408
IntType getSizeType() const
Definition TargetInfo.h:389
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:979
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:760
unsigned getTargetAddressSpace(LangAS AS) const
IntType getSignedSizeType() const
Definition TargetInfo.h:390
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...
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:227
Expr * getImmediatelyDeclaredConstraint() const
Get the immediately-declared constraint expression introduced by this type-constraint,...
Definition ASTConcept.h:244
TemplateDecl * getNamedConcept() const
Definition ASTConcept.h:254
ConceptReference * getConceptReference() const
Definition ASTConcept.h:248
Represents a declaration of a type.
Definition Decl.h:3531
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:211
Represents a typeof (or typeof) expression (a C23 feature and GCC extension) or a typeof_unqual expre...
Definition TypeBase.h:6273
A container of type source information.
Definition TypeBase.h:8407
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:267
The base class of the type hierarchy.
Definition TypeBase.h:1871
bool isBlockPointerType() const
Definition TypeBase.h:8693
bool isVoidType() const
Definition TypeBase.h:9039
bool isObjCBuiltinType() const
Definition TypeBase.h:8903
QualType getRVVEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an RVV builtin type.
Definition Type.cpp:2771
bool isIncompleteArrayType() const
Definition TypeBase.h:8780
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2266
bool isFloat16Type() const
Definition TypeBase.h:9048
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:8776
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:2517
bool isArrayType() const
Definition TypeBase.h:8772
bool isCharType() const
Definition Type.cpp:2193
QualType getLocallyUnqualifiedSingleStepDesugaredType() const
Pull a single level of sugar off of this locally-unqualified type.
Definition Type.cpp:558
bool isPointerType() const
Definition TypeBase.h:8673
TagDecl * castAsTagDecl() const
Definition Type.h:69
bool isArrayParameterType() const
Definition TypeBase.h:8788
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9083
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9333
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:9127
bool isEnumeralType() const
Definition TypeBase.h:8804
bool isObjCQualifiedIdType() const
Definition TypeBase.h:8873
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:789
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9161
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition TypeBase.h:2954
bool isBitIntType() const
Definition TypeBase.h:8948
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8796
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2837
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9099
bool isHalfType() const
Definition TypeBase.h:9043
bool isSaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9115
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition TypeBase.h:2458
QualType getCanonicalTypeInternal() const
Definition TypeBase.h:3174
@ PtrdiffT
The "ptrdiff_t" type.
Definition TypeBase.h:2333
@ SizeT
The "size_t" type.
Definition TypeBase.h:2327
@ SignedSizeT
The signed integer type corresponding to "size_t".
Definition TypeBase.h:2330
bool isObjCIdType() const
Definition TypeBase.h:8885
bool isOverflowBehaviorType() const
Definition TypeBase.h:8844
EnumDecl * castAsEnumDecl() const
Definition Type.h:59
bool isUnsaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9123
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9319
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:2527
bool isFunctionType() const
Definition TypeBase.h:8669
bool isObjCObjectPointerType() const
Definition TypeBase.h:8852
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:9141
bool isVectorType() const
Definition TypeBase.h:8812
bool isObjCClassType() const
Definition TypeBase.h:8891
bool isRVVVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'riscv_rvv_vector_bits' type attribute,...
Definition Type.cpp:2753
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition Type.cpp:2688
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2976
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:2332
bool isAnyPointerType() const
Definition TypeBase.h:8681
TypeClass getTypeClass() const
Definition TypeBase.h:2438
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition TypeBase.h:2464
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9266
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition Type.cpp:690
bool isNullPtrType() const
Definition TypeBase.h:9076
bool isRecordType() const
Definition TypeBase.h:8800
bool isObjCRetainableType() const
Definition Type.cpp:5417
NullabilityKindOrNone getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5148
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition Decl.h:3685
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition Decl.cpp:5761
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3580
QualType getUnderlyingType() const
Definition Decl.h:3635
static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TypedefNameDecl *Decl, QualType Underlying)
Definition TypeBase.h:6217
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2247
Opcode getOpcode() const
Definition Expr.h:2283
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
Definition DeclCXX.h:4460
static void Profile(llvm::FoldingSetNodeID &ID, QualType Ty, const APValue &APVal)
Definition DeclCXX.h:4488
The iterator over UnresolvedSets.
Represents the dependent type named by a dependently-scoped typename using declaration,...
Definition TypeBase.h:6078
static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const UnresolvedUsingTypenameDecl *D)
Definition TypeBase.h:6115
Represents a dependent using declaration which was marked with typename.
Definition DeclCXX.h:4042
UnresolvedUsingTypenameDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this declaration.
Definition DeclCXX.h:4107
Represents a C++ using-enum-declaration.
Definition DeclCXX.h:3797
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3404
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition DeclCXX.h:3468
BaseUsingDecl * getIntroducer() const
Gets the (written or instantiated) using declaration that introduced this declaration.
Definition DeclCXX.cpp:3479
static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const UsingShadowDecl *D, QualType UnderlyingType)
Definition TypeBase.h:6155
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
void setType(QualType newType)
Definition Decl.h:724
QualType getType() const
Definition Decl.h:723
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition Decl.cpp:5576
void clear()
Definition Value.cpp:216
Represents a variable declaration or definition.
Definition Decl.h:924
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition Decl.cpp:2789
bool hasInit() const
Definition Decl.cpp:2377
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:2440
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1296
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:1206
bool isInline() const
Whether this variable is (C++1z) inline.
Definition Decl.h:1564
@ DeclarationOnly
This declaration is only a declaration.
Definition Decl.h:1308
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition Decl.cpp:2354
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:2758
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:4021
Expr * getSizeExpr() const
Definition TypeBase.h:4035
Represents a GCC generic vector type.
Definition TypeBase.h:4230
unsigned getNumElements() const
Definition TypeBase.h:4245
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:4254
VectorKind getVectorKind() const
Definition TypeBase.h:4250
QualType getElementType() const
Definition TypeBase.h:4244
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:47
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:1830
OpenCLTypeKind
OpenCL type kinds.
Definition TargetInfo.h:213
@ OCLTK_ReserveID
Definition TargetInfo.h:220
@ OCLTK_Sampler
Definition TargetInfo.h:221
@ OCLTK_Pipe
Definition TargetInfo.h:218
@ OCLTK_ClkEvent
Definition TargetInfo.h:215
@ OCLTK_Event
Definition TargetInfo.h:216
@ OCLTK_Default
Definition TargetInfo.h:214
@ OCLTK_Queue
Definition TargetInfo.h:219
FunctionType::ExtInfo getFunctionExtInfo(const Type &t)
Definition TypeBase.h:8571
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
NullabilityKind
Describes the nullability of a particular type.
Definition Specifiers.h:349
@ Nullable
Values of this type can be null.
Definition Specifiers.h:353
@ Unspecified
Whether values of this type can be null is (explicitly) unspecified.
Definition Specifiers.h:358
@ NonNull
Values of this type can never be null.
Definition Specifiers.h:351
@ ICIS_NoInit
No in-class initializer.
Definition Specifiers.h:273
@ 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:125
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:258
@ SC_Static
Definition Specifiers.h:253
CXXABI * CreateItaniumCXXABI(ASTContext &Ctx)
Creates an instance of a C++ ABI class.
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:3774
OptionalUnsigned< unsigned > UnsignedOrNone
bool isComputedNoexcept(ExceptionSpecificationType ESpecType)
@ Template
We are parsing a template declaration.
Definition Parser.h:81
@ Interface
The "__interface" keyword.
Definition TypeBase.h:5991
@ Struct
The "struct" keyword.
Definition TypeBase.h:5988
@ Class
The "class" keyword.
Definition TypeBase.h:5997
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:490
@ Keyword
The name has been typo-corrected to a keyword.
Definition Sema.h:562
LangAS
Defines the address space values used by the address space qualifier of QualType.
TranslationUnitKind
Describes the kind of translation unit being processed.
DeducedKind
Definition TypeBase.h:1803
@ Deduced
The normal deduced case.
Definition TypeBase.h:1810
@ Undeduced
Not deduced yet. This is for example an 'auto' which was just parsed.
Definition TypeBase.h:1805
@ DeducedAsPack
Same as above, but additionally this represents a case where the deduced entity itself is a pack.
Definition TypeBase.h:1826
const Decl & adjustDeclToTemplate(const Decl &D)
If we have a 'templated' declaration for a template, adjust 'D' to refer to the actual template.
FloatModeKind
Definition TargetInfo.h:75
bool isPtrSizeAddressSpace(LangAS AS)
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:133
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:136
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition Specifiers.h:145
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:140
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1301
const StreamingDiagnostic & operator<<(const StreamingDiagnostic &DB, const ConceptReference *C)
Insertion operator for diagnostics.
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition Specifiers.h:189
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition Specifiers.h:207
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition Specifiers.h:203
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:199
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:195
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition Specifiers.h:192
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:279
@ CC_M68kRTD
Definition Specifiers.h:300
@ CC_X86RegCall
Definition Specifiers.h:288
@ CC_X86VectorCall
Definition Specifiers.h:284
@ CC_X86StdCall
Definition Specifiers.h:281
@ CC_X86FastCall
Definition Specifiers.h:282
@ 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:4200
@ SveFixedLengthData
is AArch64 SVE fixed-length data vector
Definition TypeBase.h:4209
@ AltiVecPixel
is AltiVec 'vector Pixel'
Definition TypeBase.h:4197
@ Generic
not a target-specific vector type
Definition TypeBase.h:4191
@ RVVFixedLengthData
is RISC-V RVV fixed-length data vector
Definition TypeBase.h:4215
@ RVVFixedLengthMask
is RISC-V RVV fixed-length mask vector
Definition TypeBase.h:4218
@ SveFixedLengthPredicate
is AArch64 SVE fixed-length predicate vector
Definition TypeBase.h:4212
U cast(CodeGen::Address addr)
Definition Address.h:327
LangAS getLangASFromTargetAS(unsigned TargetAS)
AlignRequirementKind
Definition ASTContext.h:178
@ None
The alignment was not explicit in code.
Definition ASTContext.h:180
@ RequiredByEnum
The alignment comes from an alignment attribute on a enum type.
Definition ASTContext.h:189
@ RequiredByTypedef
The alignment comes from an alignment attribute on a typedef.
Definition ASTContext.h:183
@ RequiredByRecord
The alignment comes from an alignment attribute on a record type.
Definition ASTContext.h:186
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition TypeBase.h:5961
@ Interface
The "__interface" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5966
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:5982
@ Struct
The "struct" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5963
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5972
@ Union
The "union" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5969
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5975
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition TypeBase.h:5979
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:88
UnsignedOrNone ArgPackSubstIndex
Definition Decl.h:89
Copy initialization expr of a __block variable and a boolean flag that indicates whether the expressi...
Definition Expr.h:6719
Expr * getCopyExpr() const
Definition Expr.h:6726
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:5419
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition TypeBase.h:5421
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition TypeBase.h:5424
Expr * NoexceptExpr
Noexcept expression, if this is a computed noexcept specification.
Definition TypeBase.h:5427
Extra information about a function prototype.
Definition TypeBase.h:5447
bool requiresFunctionProtoTypeArmAttributes() const
Definition TypeBase.h:5493
const ExtParameterInfo * ExtParameterInfos
Definition TypeBase.h:5452
bool requiresFunctionProtoTypeExtraAttributeInfo() const
Definition TypeBase.h:5497
bool requiresFunctionProtoTypeExtraBitfields() const
Definition TypeBase.h:5486
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:3381
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:147
AlignRequirementKind AlignRequirement
Definition ASTContext.h:209
bool isAlignRequired()
Definition ASTContext.h:201
AlignRequirementKind AlignRequirement
Definition ASTContext.h:195
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