clang 22.0.0git
ASTContext.cpp
Go to the documentation of this file.
1//===- ASTContext.cpp - Context to hold long-lived AST nodes --------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the ASTContext interface.
10//
11//===----------------------------------------------------------------------===//
12
14#include "ByteCode/Context.h"
15#include "CXXABI.h"
16#include "clang/AST/APValue.h"
21#include "clang/AST/Attr.h"
23#include "clang/AST/CharUnits.h"
24#include "clang/AST/Comment.h"
25#include "clang/AST/Decl.h"
26#include "clang/AST/DeclBase.h"
27#include "clang/AST/DeclCXX.h"
29#include "clang/AST/DeclObjC.h"
34#include "clang/AST/Expr.h"
35#include "clang/AST/ExprCXX.h"
37#include "clang/AST/Mangle.h"
43#include "clang/AST/Stmt.h"
46#include "clang/AST/Type.h"
47#include "clang/AST/TypeLoc.h"
55#include "clang/Basic/LLVM.h"
57#include "clang/Basic/Linkage.h"
58#include "clang/Basic/Module.h"
68#include "llvm/ADT/APFixedPoint.h"
69#include "llvm/ADT/APInt.h"
70#include "llvm/ADT/APSInt.h"
71#include "llvm/ADT/ArrayRef.h"
72#include "llvm/ADT/DenseMap.h"
73#include "llvm/ADT/DenseSet.h"
74#include "llvm/ADT/FoldingSet.h"
75#include "llvm/ADT/PointerUnion.h"
76#include "llvm/ADT/STLExtras.h"
77#include "llvm/ADT/SmallPtrSet.h"
78#include "llvm/ADT/SmallVector.h"
79#include "llvm/ADT/StringExtras.h"
80#include "llvm/ADT/StringRef.h"
81#include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
82#include "llvm/Support/Capacity.h"
83#include "llvm/Support/Casting.h"
84#include "llvm/Support/Compiler.h"
85#include "llvm/Support/ErrorHandling.h"
86#include "llvm/Support/MD5.h"
87#include "llvm/Support/MathExtras.h"
88#include "llvm/Support/SipHash.h"
89#include "llvm/Support/raw_ostream.h"
90#include "llvm/TargetParser/AArch64TargetParser.h"
91#include "llvm/TargetParser/Triple.h"
92#include <algorithm>
93#include <cassert>
94#include <cstddef>
95#include <cstdint>
96#include <cstdlib>
97#include <map>
98#include <memory>
99#include <optional>
100#include <string>
101#include <tuple>
102#include <utility>
103
104using namespace clang;
105
116
117/// \returns The locations that are relevant when searching for Doc comments
118/// related to \p D.
121 assert(D);
122
123 // User can not attach documentation to implicit declarations.
124 if (D->isImplicit())
125 return {};
126
127 // User can not attach documentation to implicit instantiations.
128 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
129 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
130 return {};
131 }
132
133 if (const auto *VD = dyn_cast<VarDecl>(D)) {
134 if (VD->isStaticDataMember() &&
135 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
136 return {};
137 }
138
139 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
140 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
141 return {};
142 }
143
144 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
145 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
146 if (TSK == TSK_ImplicitInstantiation ||
147 TSK == TSK_Undeclared)
148 return {};
149 }
150
151 if (const auto *ED = dyn_cast<EnumDecl>(D)) {
152 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
153 return {};
154 }
155 if (const auto *TD = dyn_cast<TagDecl>(D)) {
156 // When tag declaration (but not definition!) is part of the
157 // decl-specifier-seq of some other declaration, it doesn't get comment
158 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
159 return {};
160 }
161 // TODO: handle comments for function parameters properly.
162 if (isa<ParmVarDecl>(D))
163 return {};
164
165 // TODO: we could look up template parameter documentation in the template
166 // documentation.
170 return {};
171
173 // Find declaration location.
174 // For Objective-C declarations we generally don't expect to have multiple
175 // declarators, thus use declaration starting location as the "declaration
176 // location".
177 // For all other declarations multiple declarators are used quite frequently,
178 // so we use the location of the identifier as the "declaration location".
179 SourceLocation BaseLocation;
183 // Allow association with Y across {} in `typedef struct X {} Y`.
185 BaseLocation = D->getBeginLoc();
186 else
187 BaseLocation = D->getLocation();
188
189 if (!D->getLocation().isMacroID()) {
190 Locations.emplace_back(BaseLocation);
191 } else {
192 const auto *DeclCtx = D->getDeclContext();
193
194 // When encountering definitions generated from a macro (that are not
195 // contained by another declaration in the macro) we need to try and find
196 // the comment at the location of the expansion but if there is no comment
197 // there we should retry to see if there is a comment inside the macro as
198 // well. To this end we return first BaseLocation to first look at the
199 // expansion site, the second value is the spelling location of the
200 // beginning of the declaration defined inside the macro.
201 if (!(DeclCtx &&
202 Decl::castFromDeclContext(DeclCtx)->getLocation().isMacroID())) {
203 Locations.emplace_back(SourceMgr.getExpansionLoc(BaseLocation));
204 }
205
206 // We use Decl::getBeginLoc() and not just BaseLocation here to ensure that
207 // we don't refer to the macro argument location at the expansion site (this
208 // can happen if the name's spelling is provided via macro argument), and
209 // always to the declaration itself.
210 Locations.emplace_back(SourceMgr.getSpellingLoc(D->getBeginLoc()));
211 }
212
213 return Locations;
214}
215
217 const Decl *D, const SourceLocation RepresentativeLocForDecl,
218 const std::map<unsigned, RawComment *> &CommentsInTheFile) const {
219 // If the declaration doesn't map directly to a location in a file, we
220 // can't find the comment.
221 if (RepresentativeLocForDecl.isInvalid() ||
222 !RepresentativeLocForDecl.isFileID())
223 return nullptr;
224
225 // If there are no comments anywhere, we won't find anything.
226 if (CommentsInTheFile.empty())
227 return nullptr;
228
229 // Decompose the location for the declaration and find the beginning of the
230 // file buffer.
231 const FileIDAndOffset DeclLocDecomp =
232 SourceMgr.getDecomposedLoc(RepresentativeLocForDecl);
233
234 // Slow path.
235 auto OffsetCommentBehindDecl =
236 CommentsInTheFile.lower_bound(DeclLocDecomp.second);
237
238 // First check whether we have a trailing comment.
239 if (OffsetCommentBehindDecl != CommentsInTheFile.end()) {
240 RawComment *CommentBehindDecl = OffsetCommentBehindDecl->second;
241 if ((CommentBehindDecl->isDocumentation() ||
242 LangOpts.CommentOpts.ParseAllComments) &&
243 CommentBehindDecl->isTrailingComment() &&
246
247 // Check that Doxygen trailing comment comes after the declaration, starts
248 // on the same line and in the same file as the declaration.
249 if (SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second) ==
250 Comments.getCommentBeginLine(CommentBehindDecl, DeclLocDecomp.first,
251 OffsetCommentBehindDecl->first)) {
252 return CommentBehindDecl;
253 }
254 }
255 }
256
257 // The comment just after the declaration was not a trailing comment.
258 // Let's look at the previous comment.
259 if (OffsetCommentBehindDecl == CommentsInTheFile.begin())
260 return nullptr;
261
262 auto OffsetCommentBeforeDecl = --OffsetCommentBehindDecl;
263 RawComment *CommentBeforeDecl = OffsetCommentBeforeDecl->second;
264
265 // Check that we actually have a non-member Doxygen comment.
266 if (!(CommentBeforeDecl->isDocumentation() ||
267 LangOpts.CommentOpts.ParseAllComments) ||
268 CommentBeforeDecl->isTrailingComment())
269 return nullptr;
270
271 // Decompose the end of the comment.
272 const unsigned CommentEndOffset =
273 Comments.getCommentEndOffset(CommentBeforeDecl);
274
275 // Get the corresponding buffer.
276 bool Invalid = false;
277 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
278 &Invalid).data();
279 if (Invalid)
280 return nullptr;
281
282 // Extract text between the comment and declaration.
283 StringRef Text(Buffer + CommentEndOffset,
284 DeclLocDecomp.second - CommentEndOffset);
285
286 // There should be no other declarations or preprocessor directives between
287 // comment and declaration.
288 if (Text.find_last_of(";{}#@") != StringRef::npos)
289 return nullptr;
290
291 return CommentBeforeDecl;
292}
293
295 const auto DeclLocs = getDeclLocsForCommentSearch(D, SourceMgr);
296
297 for (const auto DeclLoc : DeclLocs) {
298 // If the declaration doesn't map directly to a location in a file, we
299 // can't find the comment.
300 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
301 continue;
302
304 ExternalSource->ReadComments();
305 CommentsLoaded = true;
306 }
307
308 if (Comments.empty())
309 continue;
310
311 const FileID File = SourceMgr.getDecomposedLoc(DeclLoc).first;
312 if (!File.isValid())
313 continue;
314
315 const auto CommentsInThisFile = Comments.getCommentsInFile(File);
316 if (!CommentsInThisFile || CommentsInThisFile->empty())
317 continue;
318
319 if (RawComment *Comment =
320 getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile))
321 return Comment;
322 }
323
324 return nullptr;
325}
326
328 assert(LangOpts.RetainCommentsFromSystemHeaders ||
329 !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin()));
330 Comments.addComment(RC, LangOpts.CommentOpts, BumpAlloc);
331}
332
334 const Decl *D,
335 const Decl **OriginalDecl) const {
336 if (!D) {
337 if (OriginalDecl)
338 OriginalDecl = nullptr;
339 return nullptr;
340 }
341
342 D = &adjustDeclToTemplate(*D);
343
344 // Any comment directly attached to D?
345 {
346 auto DeclComment = DeclRawComments.find(D);
347 if (DeclComment != DeclRawComments.end()) {
348 if (OriginalDecl)
349 *OriginalDecl = D;
350 return DeclComment->second;
351 }
352 }
353
354 // Any comment attached to any redeclaration of D?
355 const Decl *CanonicalD = D->getCanonicalDecl();
356 if (!CanonicalD)
357 return nullptr;
358
359 {
360 auto RedeclComment = RedeclChainComments.find(CanonicalD);
361 if (RedeclComment != RedeclChainComments.end()) {
362 if (OriginalDecl)
363 *OriginalDecl = RedeclComment->second;
364 auto CommentAtRedecl = DeclRawComments.find(RedeclComment->second);
365 assert(CommentAtRedecl != DeclRawComments.end() &&
366 "This decl is supposed to have comment attached.");
367 return CommentAtRedecl->second;
368 }
369 }
370
371 // Any redeclarations of D that we haven't checked for comments yet?
372 const Decl *LastCheckedRedecl = [&]() {
373 const Decl *LastChecked = CommentlessRedeclChains.lookup(CanonicalD);
374 bool CanUseCommentlessCache = false;
375 if (LastChecked) {
376 for (auto *Redecl : CanonicalD->redecls()) {
377 if (Redecl == D) {
378 CanUseCommentlessCache = true;
379 break;
380 }
381 if (Redecl == LastChecked)
382 break;
383 }
384 }
385 // FIXME: This could be improved so that even if CanUseCommentlessCache
386 // is false, once we've traversed past CanonicalD we still skip ahead
387 // LastChecked.
388 return CanUseCommentlessCache ? LastChecked : nullptr;
389 }();
390
391 for (const Decl *Redecl : D->redecls()) {
392 assert(Redecl);
393 // Skip all redeclarations that have been checked previously.
394 if (LastCheckedRedecl) {
395 if (LastCheckedRedecl == Redecl) {
396 LastCheckedRedecl = nullptr;
397 }
398 continue;
399 }
400 const RawComment *RedeclComment = getRawCommentForDeclNoCache(Redecl);
401 if (RedeclComment) {
402 cacheRawCommentForDecl(*Redecl, *RedeclComment);
403 if (OriginalDecl)
404 *OriginalDecl = Redecl;
405 return RedeclComment;
406 }
407 CommentlessRedeclChains[CanonicalD] = Redecl;
408 }
409
410 if (OriginalDecl)
411 *OriginalDecl = nullptr;
412 return nullptr;
413}
414
416 const RawComment &Comment) const {
417 assert(Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
418 DeclRawComments.try_emplace(&OriginalD, &Comment);
419 const Decl *const CanonicalDecl = OriginalD.getCanonicalDecl();
420 RedeclChainComments.try_emplace(CanonicalDecl, &OriginalD);
421 CommentlessRedeclChains.erase(CanonicalDecl);
422}
423
424static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
426 const DeclContext *DC = ObjCMethod->getDeclContext();
427 if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) {
428 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
429 if (!ID)
430 return;
431 // Add redeclared method here.
432 for (const auto *Ext : ID->known_extensions()) {
433 if (ObjCMethodDecl *RedeclaredMethod =
434 Ext->getMethod(ObjCMethod->getSelector(),
435 ObjCMethod->isInstanceMethod()))
436 Redeclared.push_back(RedeclaredMethod);
437 }
438 }
439}
440
442 const Preprocessor *PP) {
443 if (Comments.empty() || Decls.empty())
444 return;
445
446 FileID File;
447 for (const Decl *D : Decls) {
448 if (D->isInvalidDecl())
449 continue;
450
451 D = &adjustDeclToTemplate(*D);
452 SourceLocation Loc = D->getLocation();
453 if (Loc.isValid()) {
454 // See if there are any new comments that are not attached to a decl.
455 // The location doesn't have to be precise - we care only about the file.
456 File = SourceMgr.getDecomposedLoc(Loc).first;
457 break;
458 }
459 }
460
461 if (File.isInvalid())
462 return;
463
464 auto CommentsInThisFile = Comments.getCommentsInFile(File);
465 if (!CommentsInThisFile || CommentsInThisFile->empty() ||
466 CommentsInThisFile->rbegin()->second->isAttached())
467 return;
468
469 // There is at least one comment not attached to a decl.
470 // Maybe it should be attached to one of Decls?
471 //
472 // Note that this way we pick up not only comments that precede the
473 // declaration, but also comments that *follow* the declaration -- thanks to
474 // the lookahead in the lexer: we've consumed the semicolon and looked
475 // ahead through comments.
476 for (const Decl *D : Decls) {
477 assert(D);
478 if (D->isInvalidDecl())
479 continue;
480
481 D = &adjustDeclToTemplate(*D);
482
483 if (DeclRawComments.count(D) > 0)
484 continue;
485
486 const auto DeclLocs = getDeclLocsForCommentSearch(D, SourceMgr);
487
488 for (const auto DeclLoc : DeclLocs) {
489 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
490 continue;
491
492 if (RawComment *const DocComment = getRawCommentForDeclNoCacheImpl(
493 D, DeclLoc, *CommentsInThisFile)) {
494 cacheRawCommentForDecl(*D, *DocComment);
495 comments::FullComment *FC = DocComment->parse(*this, PP, D);
496 ParsedComments[D->getCanonicalDecl()] = FC;
497 break;
498 }
499 }
500 }
501}
502
504 const Decl *D) const {
505 auto *ThisDeclInfo = new (*this) comments::DeclInfo;
506 ThisDeclInfo->CommentDecl = D;
507 ThisDeclInfo->IsFilled = false;
508 ThisDeclInfo->fill();
509 ThisDeclInfo->CommentDecl = FC->getDecl();
510 if (!ThisDeclInfo->TemplateParameters)
511 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
513 new (*this) comments::FullComment(FC->getBlocks(),
514 ThisDeclInfo);
515 return CFC;
516}
517
520 return RC ? RC->parse(*this, nullptr, D) : nullptr;
521}
522
524 const Decl *D,
525 const Preprocessor *PP) const {
526 if (!D || D->isInvalidDecl())
527 return nullptr;
528 D = &adjustDeclToTemplate(*D);
529
530 const Decl *Canonical = D->getCanonicalDecl();
531 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
532 ParsedComments.find(Canonical);
533
534 if (Pos != ParsedComments.end()) {
535 if (Canonical != D) {
536 comments::FullComment *FC = Pos->second;
538 return CFC;
539 }
540 return Pos->second;
541 }
542
543 const Decl *OriginalDecl = nullptr;
544
545 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
546 if (!RC) {
549 const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
550 if (OMD && OMD->isPropertyAccessor())
551 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
552 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
553 return cloneFullComment(FC, D);
554 if (OMD)
555 addRedeclaredMethods(OMD, Overridden);
556 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
557 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
558 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
559 return cloneFullComment(FC, D);
560 }
561 else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
562 // Attach any tag type's documentation to its typedef if latter
563 // does not have one of its own.
564 QualType QT = TD->getUnderlyingType();
565 if (const auto *TT = QT->getAs<TagType>())
566 if (comments::FullComment *FC = getCommentForDecl(TT->getDecl(), PP))
567 return cloneFullComment(FC, D);
568 }
569 else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
570 while (IC->getSuperClass()) {
571 IC = IC->getSuperClass();
573 return cloneFullComment(FC, D);
574 }
575 }
576 else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) {
577 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
579 return cloneFullComment(FC, D);
580 }
581 else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
582 if (!(RD = RD->getDefinition()))
583 return nullptr;
584 // Check non-virtual bases.
585 for (const auto &I : RD->bases()) {
586 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
587 continue;
588 QualType Ty = I.getType();
589 if (Ty.isNull())
590 continue;
592 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
593 continue;
594
596 return cloneFullComment(FC, D);
597 }
598 }
599 // Check virtual bases.
600 for (const auto &I : RD->vbases()) {
601 if (I.getAccessSpecifier() != AS_public)
602 continue;
603 QualType Ty = I.getType();
604 if (Ty.isNull())
605 continue;
606 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
607 if (!(VirtualBase= VirtualBase->getDefinition()))
608 continue;
610 return cloneFullComment(FC, D);
611 }
612 }
613 }
614 return nullptr;
615 }
616
617 // If the RawComment was attached to other redeclaration of this Decl, we
618 // should parse the comment in context of that other Decl. This is important
619 // because comments can contain references to parameter names which can be
620 // different across redeclarations.
621 if (D != OriginalDecl && OriginalDecl)
622 return getCommentForDecl(OriginalDecl, PP);
623
624 comments::FullComment *FC = RC->parse(*this, PP, D);
625 ParsedComments[Canonical] = FC;
626 return FC;
627}
628
629void ASTContext::CanonicalTemplateTemplateParm::Profile(
630 llvm::FoldingSetNodeID &ID, const ASTContext &C,
632 ID.AddInteger(Parm->getDepth());
633 ID.AddInteger(Parm->getPosition());
634 ID.AddBoolean(Parm->isParameterPack());
635 ID.AddInteger(Parm->templateParameterKind());
636
638 ID.AddInteger(Params->size());
640 PEnd = Params->end();
641 P != PEnd; ++P) {
642 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
643 ID.AddInteger(0);
644 ID.AddBoolean(TTP->isParameterPack());
645 ID.AddInteger(
646 TTP->getNumExpansionParameters().toInternalRepresentation());
647 continue;
648 }
649
650 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
651 ID.AddInteger(1);
652 ID.AddBoolean(NTTP->isParameterPack());
653 ID.AddPointer(C.getUnconstrainedType(C.getCanonicalType(NTTP->getType()))
654 .getAsOpaquePtr());
655 if (NTTP->isExpandedParameterPack()) {
656 ID.AddBoolean(true);
657 ID.AddInteger(NTTP->getNumExpansionTypes());
658 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
659 QualType T = NTTP->getExpansionType(I);
660 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
661 }
662 } else
663 ID.AddBoolean(false);
664 continue;
665 }
666
667 auto *TTP = cast<TemplateTemplateParmDecl>(*P);
668 ID.AddInteger(2);
669 Profile(ID, C, TTP);
670 }
671}
672
673TemplateTemplateParmDecl *
675 TemplateTemplateParmDecl *TTP) const {
676 // Check if we already have a canonical template template parameter.
677 llvm::FoldingSetNodeID ID;
678 CanonicalTemplateTemplateParm::Profile(ID, *this, TTP);
679 void *InsertPos = nullptr;
680 CanonicalTemplateTemplateParm *Canonical
681 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
682 if (Canonical)
683 return Canonical->getParam();
684
685 // Build a canonical template parameter list.
687 SmallVector<NamedDecl *, 4> CanonParams;
688 CanonParams.reserve(Params->size());
690 PEnd = Params->end();
691 P != PEnd; ++P) {
692 // Note that, per C++20 [temp.over.link]/6, when determining whether
693 // template-parameters are equivalent, constraints are ignored.
694 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
697 TTP->getDepth(), TTP->getIndex(), nullptr, false,
698 TTP->isParameterPack(), /*HasTypeConstraint=*/false,
699 TTP->getNumExpansionParameters());
700 CanonParams.push_back(NewTTP);
701 } else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
705 if (NTTP->isExpandedParameterPack()) {
706 SmallVector<QualType, 2> ExpandedTypes;
708 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
709 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
710 ExpandedTInfos.push_back(
711 getTrivialTypeSourceInfo(ExpandedTypes.back()));
712 }
713
717 NTTP->getDepth(),
718 NTTP->getPosition(), nullptr,
719 T,
720 TInfo,
721 ExpandedTypes,
722 ExpandedTInfos);
723 } else {
727 NTTP->getDepth(),
728 NTTP->getPosition(), nullptr,
729 T,
730 NTTP->isParameterPack(),
731 TInfo);
732 }
733 CanonParams.push_back(Param);
734 } else
735 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
737 }
738
741 TTP->getPosition(), TTP->isParameterPack(), nullptr,
743 /*Typename=*/false,
745 CanonParams, SourceLocation(),
746 /*RequiresClause=*/nullptr));
747
748 // Get the new insert position for the node we care about.
749 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
750 assert(!Canonical && "Shouldn't be in the map!");
751 (void)Canonical;
752
753 // Create the canonical template template parameter entry.
754 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
755 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
756 return CanonTTP;
757}
758
761 TemplateTemplateParmDecl *TTP) const {
762 llvm::FoldingSetNodeID ID;
763 CanonicalTemplateTemplateParm::Profile(ID, *this, TTP);
764 void *InsertPos = nullptr;
765 CanonicalTemplateTemplateParm *Canonical =
766 CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
767 return Canonical ? Canonical->getParam() : nullptr;
768}
769
772 TemplateTemplateParmDecl *CanonTTP) const {
773 llvm::FoldingSetNodeID ID;
774 CanonicalTemplateTemplateParm::Profile(ID, *this, CanonTTP);
775 void *InsertPos = nullptr;
776 if (auto *Existing =
777 CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos))
778 return Existing->getParam();
779 CanonTemplateTemplateParms.InsertNode(
780 new (*this) CanonicalTemplateTemplateParm(CanonTTP), InsertPos);
781 return CanonTTP;
782}
783
784/// Check if a type can have its sanitizer instrumentation elided based on its
785/// presence within an ignorelist.
787 const QualType &Ty) const {
788 std::string TyName = Ty.getUnqualifiedType().getAsString(getPrintingPolicy());
789 return NoSanitizeL->containsType(Mask, TyName);
790}
791
793 auto Kind = getTargetInfo().getCXXABI().getKind();
794 return getLangOpts().CXXABI.value_or(Kind);
795}
796
797CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
798 if (!LangOpts.CPlusPlus) return nullptr;
799
800 switch (getCXXABIKind()) {
801 case TargetCXXABI::AppleARM64:
802 case TargetCXXABI::Fuchsia:
803 case TargetCXXABI::GenericARM: // Same as Itanium at this level
804 case TargetCXXABI::iOS:
805 case TargetCXXABI::WatchOS:
806 case TargetCXXABI::GenericAArch64:
807 case TargetCXXABI::GenericMIPS:
808 case TargetCXXABI::GenericItanium:
809 case TargetCXXABI::WebAssembly:
810 case TargetCXXABI::XL:
811 return CreateItaniumCXXABI(*this);
812 case TargetCXXABI::Microsoft:
813 return CreateMicrosoftCXXABI(*this);
814 }
815 llvm_unreachable("Invalid CXXABI type!");
816}
817
819 if (!InterpContext) {
820 InterpContext.reset(new interp::Context(*this));
821 }
822 return *InterpContext;
823}
824
826 if (!ParentMapCtx)
827 ParentMapCtx.reset(new ParentMapContext(*this));
828 return *ParentMapCtx;
829}
830
832 const LangOptions &LangOpts) {
833 switch (LangOpts.getAddressSpaceMapMangling()) {
835 return TI.useAddressSpaceMapMangling();
837 return true;
839 return false;
840 }
841 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
842}
843
845 IdentifierTable &idents, SelectorTable &sels,
847 : ConstantArrayTypes(this_(), ConstantArrayTypesLog2InitSize),
848 DependentSizedArrayTypes(this_()), DependentSizedExtVectorTypes(this_()),
849 DependentAddressSpaceTypes(this_()), DependentVectorTypes(this_()),
850 DependentSizedMatrixTypes(this_()),
851 FunctionProtoTypes(this_(), FunctionProtoTypesLog2InitSize),
852 DependentTypeOfExprTypes(this_()), DependentDecltypeTypes(this_()),
853 DependentPackIndexingTypes(this_()), TemplateSpecializationTypes(this_()),
854 DependentBitIntTypes(this_()), SubstTemplateTemplateParmPacks(this_()),
855 DeducedTemplates(this_()), ArrayParameterTypes(this_()),
856 CanonTemplateTemplateParms(this_()), SourceMgr(SM), LangOpts(LOpts),
857 NoSanitizeL(new NoSanitizeList(LangOpts.NoSanitizeFiles, SM)),
858 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
859 LangOpts.XRayNeverInstrumentFiles,
860 LangOpts.XRayAttrListFiles, SM)),
861 ProfList(new ProfileList(LangOpts.ProfileListFiles, SM)),
862 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
863 BuiltinInfo(builtins), TUKind(TUKind), DeclarationNames(*this),
864 Comments(SM), CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
865 CompCategories(this_()), LastSDM(nullptr, 0) {
867}
868
870 // Release the DenseMaps associated with DeclContext objects.
871 // FIXME: Is this the ideal solution?
872 ReleaseDeclContextMaps();
873
874 // Call all of the deallocation functions on all of their targets.
875 for (auto &Pair : Deallocations)
876 (Pair.first)(Pair.second);
877 Deallocations.clear();
878
879 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
880 // because they can contain DenseMaps.
881 for (llvm::DenseMap<const ObjCInterfaceDecl *,
883 I = ObjCLayouts.begin(),
884 E = ObjCLayouts.end();
885 I != E;)
886 // Increment in loop to prevent using deallocated memory.
887 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
888 R->Destroy(*this);
889 ObjCLayouts.clear();
890
891 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
892 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
893 // Increment in loop to prevent using deallocated memory.
894 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
895 R->Destroy(*this);
896 }
897 ASTRecordLayouts.clear();
898
899 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
900 AEnd = DeclAttrs.end();
901 A != AEnd; ++A)
902 A->second->~AttrVec();
903 DeclAttrs.clear();
904
905 for (const auto &Value : ModuleInitializers)
906 Value.second->~PerModuleInitializers();
907 ModuleInitializers.clear();
908
909 XRayFilter.reset();
910 NoSanitizeL.reset();
911}
912
914
915void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
916 TraversalScope = TopLevelDecls;
918}
919
920void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const {
921 Deallocations.push_back({Callback, Data});
922}
923
924void
928
930 llvm::errs() << "\n*** AST Context Stats:\n";
931 llvm::errs() << " " << Types.size() << " types total.\n";
932
933 unsigned counts[] = {
934#define TYPE(Name, Parent) 0,
935#define ABSTRACT_TYPE(Name, Parent)
936#include "clang/AST/TypeNodes.inc"
937 0 // Extra
938 };
939
940 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
941 Type *T = Types[i];
942 counts[(unsigned)T->getTypeClass()]++;
943 }
944
945 unsigned Idx = 0;
946 unsigned TotalBytes = 0;
947#define TYPE(Name, Parent) \
948 if (counts[Idx]) \
949 llvm::errs() << " " << counts[Idx] << " " << #Name \
950 << " types, " << sizeof(Name##Type) << " each " \
951 << "(" << counts[Idx] * sizeof(Name##Type) \
952 << " bytes)\n"; \
953 TotalBytes += counts[Idx] * sizeof(Name##Type); \
954 ++Idx;
955#define ABSTRACT_TYPE(Name, Parent)
956#include "clang/AST/TypeNodes.inc"
957
958 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
959
960 // Implicit special member functions.
961 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
963 << " implicit default constructors created\n";
964 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
966 << " implicit copy constructors created\n";
968 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
970 << " implicit move constructors created\n";
971 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
973 << " implicit copy assignment operators created\n";
975 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
977 << " implicit move assignment operators created\n";
978 llvm::errs() << NumImplicitDestructorsDeclared << "/"
980 << " implicit destructors created\n";
981
982 if (ExternalSource) {
983 llvm::errs() << "\n";
984 ExternalSource->PrintStats();
985 }
986
987 BumpAlloc.PrintStats();
988}
989
991 bool NotifyListeners) {
992 if (NotifyListeners)
993 if (auto *Listener = getASTMutationListener();
995 Listener->RedefinedHiddenDefinition(ND, M);
996
997 MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M);
998}
999
1001 auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl()));
1002 if (It == MergedDefModules.end())
1003 return;
1004
1005 auto &Merged = It->second;
1006 llvm::DenseSet<Module*> Found;
1007 for (Module *&M : Merged)
1008 if (!Found.insert(M).second)
1009 M = nullptr;
1010 llvm::erase(Merged, nullptr);
1011}
1012
1015 auto MergedIt =
1016 MergedDefModules.find(cast<NamedDecl>(Def->getCanonicalDecl()));
1017 if (MergedIt == MergedDefModules.end())
1018 return {};
1019 return MergedIt->second;
1020}
1021
1022void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
1023 if (LazyInitializers.empty())
1024 return;
1025
1026 auto *Source = Ctx.getExternalSource();
1027 assert(Source && "lazy initializers but no external source");
1028
1029 auto LazyInits = std::move(LazyInitializers);
1030 LazyInitializers.clear();
1031
1032 for (auto ID : LazyInits)
1033 Initializers.push_back(Source->GetExternalDecl(ID));
1034
1035 assert(LazyInitializers.empty() &&
1036 "GetExternalDecl for lazy module initializer added more inits");
1037}
1038
1040 // One special case: if we add a module initializer that imports another
1041 // module, and that module's only initializer is an ImportDecl, simplify.
1042 if (const auto *ID = dyn_cast<ImportDecl>(D)) {
1043 auto It = ModuleInitializers.find(ID->getImportedModule());
1044
1045 // Maybe the ImportDecl does nothing at all. (Common case.)
1046 if (It == ModuleInitializers.end())
1047 return;
1048
1049 // Maybe the ImportDecl only imports another ImportDecl.
1050 auto &Imported = *It->second;
1051 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
1052 Imported.resolve(*this);
1053 auto *OnlyDecl = Imported.Initializers.front();
1054 if (isa<ImportDecl>(OnlyDecl))
1055 D = OnlyDecl;
1056 }
1057 }
1058
1059 auto *&Inits = ModuleInitializers[M];
1060 if (!Inits)
1061 Inits = new (*this) PerModuleInitializers;
1062 Inits->Initializers.push_back(D);
1063}
1064
1067 auto *&Inits = ModuleInitializers[M];
1068 if (!Inits)
1069 Inits = new (*this) PerModuleInitializers;
1070 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
1071 IDs.begin(), IDs.end());
1072}
1073
1075 auto It = ModuleInitializers.find(M);
1076 if (It == ModuleInitializers.end())
1077 return {};
1078
1079 auto *Inits = It->second;
1080 Inits->resolve(*this);
1081 return Inits->Initializers;
1082}
1083
1085 assert(M->isNamedModule());
1086 assert(!CurrentCXXNamedModule &&
1087 "We should set named module for ASTContext for only once");
1088 CurrentCXXNamedModule = M;
1089}
1090
1091bool ASTContext::isInSameModule(const Module *M1, const Module *M2) const {
1092 if (!M1 != !M2)
1093 return false;
1094
1095 /// Get the representative module for M. The representative module is the
1096 /// first module unit for a specific primary module name. So that the module
1097 /// units have the same representative module belongs to the same module.
1098 ///
1099 /// The process is helpful to reduce the expensive string operations.
1100 auto GetRepresentativeModule = [this](const Module *M) {
1101 auto Iter = SameModuleLookupSet.find(M);
1102 if (Iter != SameModuleLookupSet.end())
1103 return Iter->second;
1104
1105 const Module *RepresentativeModule =
1106 PrimaryModuleNameMap.try_emplace(M->getPrimaryModuleInterfaceName(), M)
1107 .first->second;
1108 SameModuleLookupSet[M] = RepresentativeModule;
1109 return RepresentativeModule;
1110 };
1111
1112 assert(M1 && "Shouldn't call `isInSameModule` if both M1 and M2 are none.");
1113 return GetRepresentativeModule(M1) == GetRepresentativeModule(M2);
1114}
1115
1117 if (!ExternCContext)
1118 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1119
1120 return ExternCContext;
1121}
1122
1133
1134#define BuiltinTemplate(BTName) \
1135 BuiltinTemplateDecl *ASTContext::get##BTName##Decl() const { \
1136 if (!Decl##BTName) \
1137 Decl##BTName = \
1138 buildBuiltinTemplateDecl(BTK##BTName, get##BTName##Name()); \
1139 return Decl##BTName; \
1140 }
1141#include "clang/Basic/BuiltinTemplates.inc"
1142
1144 RecordDecl::TagKind TK) const {
1145 SourceLocation Loc;
1146 RecordDecl *NewDecl;
1147 if (getLangOpts().CPlusPlus)
1148 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1149 Loc, &Idents.get(Name));
1150 else
1151 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1152 &Idents.get(Name));
1153 NewDecl->setImplicit();
1154 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1155 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
1156 return NewDecl;
1157}
1158
1160 StringRef Name) const {
1163 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1164 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1165 NewDecl->setImplicit();
1166 return NewDecl;
1167}
1168
1170 if (!Int128Decl)
1171 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
1172 return Int128Decl;
1173}
1174
1176 if (!UInt128Decl)
1177 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
1178 return UInt128Decl;
1179}
1180
1181void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
1182 auto *Ty = new (*this, alignof(BuiltinType)) BuiltinType(K);
1184 Types.push_back(Ty);
1185}
1186
1188 const TargetInfo *AuxTarget) {
1189 assert((!this->Target || this->Target == &Target) &&
1190 "Incorrect target reinitialization");
1191 assert(VoidTy.isNull() && "Context reinitialized?");
1192
1193 this->Target = &Target;
1194 this->AuxTarget = AuxTarget;
1195
1196 ABI.reset(createCXXABI(Target));
1197 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
1198
1199 // C99 6.2.5p19.
1200 InitBuiltinType(VoidTy, BuiltinType::Void);
1201
1202 // C99 6.2.5p2.
1203 InitBuiltinType(BoolTy, BuiltinType::Bool);
1204 // C99 6.2.5p3.
1205 if (LangOpts.CharIsSigned)
1206 InitBuiltinType(CharTy, BuiltinType::Char_S);
1207 else
1208 InitBuiltinType(CharTy, BuiltinType::Char_U);
1209 // C99 6.2.5p4.
1210 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1211 InitBuiltinType(ShortTy, BuiltinType::Short);
1212 InitBuiltinType(IntTy, BuiltinType::Int);
1213 InitBuiltinType(LongTy, BuiltinType::Long);
1214 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
1215
1216 // C99 6.2.5p6.
1217 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1218 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1219 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1220 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1221 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
1222
1223 // C99 6.2.5p10.
1224 InitBuiltinType(FloatTy, BuiltinType::Float);
1225 InitBuiltinType(DoubleTy, BuiltinType::Double);
1226 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
1227
1228 // GNU extension, __float128 for IEEE quadruple precision
1229 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1230
1231 // __ibm128 for IBM extended precision
1232 InitBuiltinType(Ibm128Ty, BuiltinType::Ibm128);
1233
1234 // C11 extension ISO/IEC TS 18661-3
1235 InitBuiltinType(Float16Ty, BuiltinType::Float16);
1236
1237 // ISO/IEC JTC1 SC22 WG14 N1169 Extension
1238 InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum);
1239 InitBuiltinType(AccumTy, BuiltinType::Accum);
1240 InitBuiltinType(LongAccumTy, BuiltinType::LongAccum);
1241 InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum);
1242 InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum);
1243 InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum);
1244 InitBuiltinType(ShortFractTy, BuiltinType::ShortFract);
1245 InitBuiltinType(FractTy, BuiltinType::Fract);
1246 InitBuiltinType(LongFractTy, BuiltinType::LongFract);
1247 InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract);
1248 InitBuiltinType(UnsignedFractTy, BuiltinType::UFract);
1249 InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract);
1250 InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum);
1251 InitBuiltinType(SatAccumTy, BuiltinType::SatAccum);
1252 InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum);
1253 InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
1254 InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum);
1255 InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum);
1256 InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract);
1257 InitBuiltinType(SatFractTy, BuiltinType::SatFract);
1258 InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract);
1259 InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
1260 InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract);
1261 InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract);
1262
1263 // GNU extension, 128-bit integers.
1264 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1265 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1266
1267 // C++ 3.9.1p5
1268 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1269 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1270 else // -fshort-wchar makes wchar_t be unsigned.
1271 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1272 if (LangOpts.CPlusPlus && LangOpts.WChar)
1274 else {
1275 // C99 (or C++ using -fno-wchar).
1276 WideCharTy = getFromTargetType(Target.getWCharType());
1277 }
1278
1279 WIntTy = getFromTargetType(Target.getWIntType());
1280
1281 // C++20 (proposed)
1282 InitBuiltinType(Char8Ty, BuiltinType::Char8);
1283
1284 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1285 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1286 else // C99
1287 Char16Ty = getFromTargetType(Target.getChar16Type());
1288
1289 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1290 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1291 else // C99
1292 Char32Ty = getFromTargetType(Target.getChar32Type());
1293
1294 // Placeholder type for type-dependent expressions whose type is
1295 // completely unknown. No code should ever check a type against
1296 // DependentTy and users should never see it; however, it is here to
1297 // help diagnose failures to properly check for type-dependent
1298 // expressions.
1299 InitBuiltinType(DependentTy, BuiltinType::Dependent);
1300
1301 // Placeholder type for functions.
1302 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1303
1304 // Placeholder type for bound members.
1305 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1306
1307 // Placeholder type for unresolved templates.
1308 InitBuiltinType(UnresolvedTemplateTy, BuiltinType::UnresolvedTemplate);
1309
1310 // Placeholder type for pseudo-objects.
1311 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1312
1313 // "any" type; useful for debugger-like clients.
1314 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1315
1316 // Placeholder type for unbridged ARC casts.
1317 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1318
1319 // Placeholder type for builtin functions.
1320 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1321
1322 // Placeholder type for OMP array sections.
1323 if (LangOpts.OpenMP) {
1324 InitBuiltinType(ArraySectionTy, BuiltinType::ArraySection);
1325 InitBuiltinType(OMPArrayShapingTy, BuiltinType::OMPArrayShaping);
1326 InitBuiltinType(OMPIteratorTy, BuiltinType::OMPIterator);
1327 }
1328 // Placeholder type for OpenACC array sections, if we are ALSO in OMP mode,
1329 // don't bother, as we're just using the same type as OMP.
1330 if (LangOpts.OpenACC && !LangOpts.OpenMP) {
1331 InitBuiltinType(ArraySectionTy, BuiltinType::ArraySection);
1332 }
1333 if (LangOpts.MatrixTypes)
1334 InitBuiltinType(IncompleteMatrixIdxTy, BuiltinType::IncompleteMatrixIdx);
1335
1336 // Builtin types for 'id', 'Class', and 'SEL'.
1337 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1338 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
1339 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
1340
1341 if (LangOpts.OpenCL) {
1342#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1343 InitBuiltinType(SingletonId, BuiltinType::Id);
1344#include "clang/Basic/OpenCLImageTypes.def"
1345
1346 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
1347 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
1348 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1349 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1350 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
1351
1352#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1353 InitBuiltinType(Id##Ty, BuiltinType::Id);
1354#include "clang/Basic/OpenCLExtensionTypes.def"
1355 }
1356
1357 if (LangOpts.HLSL) {
1358#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
1359 InitBuiltinType(SingletonId, BuiltinType::Id);
1360#include "clang/Basic/HLSLIntangibleTypes.def"
1361 }
1362
1363 if (Target.hasAArch64ACLETypes() ||
1364 (AuxTarget && AuxTarget->hasAArch64ACLETypes())) {
1365#define SVE_TYPE(Name, Id, SingletonId) \
1366 InitBuiltinType(SingletonId, BuiltinType::Id);
1367#include "clang/Basic/AArch64ACLETypes.def"
1368 }
1369
1370 if (Target.getTriple().isPPC64()) {
1371#define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
1372 InitBuiltinType(Id##Ty, BuiltinType::Id);
1373#include "clang/Basic/PPCTypes.def"
1374#define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
1375 InitBuiltinType(Id##Ty, BuiltinType::Id);
1376#include "clang/Basic/PPCTypes.def"
1377 }
1378
1379 if (Target.hasRISCVVTypes()) {
1380#define RVV_TYPE(Name, Id, SingletonId) \
1381 InitBuiltinType(SingletonId, BuiltinType::Id);
1382#include "clang/Basic/RISCVVTypes.def"
1383 }
1384
1385 if (Target.getTriple().isWasm() && Target.hasFeature("reference-types")) {
1386#define WASM_TYPE(Name, Id, SingletonId) \
1387 InitBuiltinType(SingletonId, BuiltinType::Id);
1388#include "clang/Basic/WebAssemblyReferenceTypes.def"
1389 }
1390
1391 if (Target.getTriple().isAMDGPU() ||
1392 (AuxTarget && AuxTarget->getTriple().isAMDGPU())) {
1393#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) \
1394 InitBuiltinType(SingletonId, BuiltinType::Id);
1395#include "clang/Basic/AMDGPUTypes.def"
1396 }
1397
1398 // Builtin type for __objc_yes and __objc_no
1399 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1401
1402 ObjCConstantStringType = QualType();
1403
1404 ObjCSuperType = QualType();
1405
1406 // void * type
1407 if (LangOpts.OpenCLGenericAddressSpace) {
1408 auto Q = VoidTy.getQualifiers();
1409 Q.setAddressSpace(LangAS::opencl_generic);
1411 getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
1412 } else {
1414 }
1415
1416 // nullptr type (C++0x 2.14.7)
1417 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
1418
1419 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1420 InitBuiltinType(HalfTy, BuiltinType::Half);
1421
1422 InitBuiltinType(BFloat16Ty, BuiltinType::BFloat16);
1423
1424 // Builtin type used to help define __builtin_va_list.
1425 VaListTagDecl = nullptr;
1426
1427 // MSVC predeclares struct _GUID, and we need it to create MSGuidDecls.
1428 if (LangOpts.MicrosoftExt || LangOpts.Borland) {
1431 }
1432}
1433
1435 return SourceMgr.getDiagnostics();
1436}
1437
1439 AttrVec *&Result = DeclAttrs[D];
1440 if (!Result) {
1441 void *Mem = Allocate(sizeof(AttrVec));
1442 Result = new (Mem) AttrVec;
1443 }
1444
1445 return *Result;
1446}
1447
1448/// Erase the attributes corresponding to the given declaration.
1450 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1451 if (Pos != DeclAttrs.end()) {
1452 Pos->second->~AttrVec();
1453 DeclAttrs.erase(Pos);
1454 }
1455}
1456
1457// FIXME: Remove ?
1460 assert(Var->isStaticDataMember() && "Not a static data member");
1462 .dyn_cast<MemberSpecializationInfo *>();
1463}
1464
1467 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1468 TemplateOrInstantiation.find(Var);
1469 if (Pos == TemplateOrInstantiation.end())
1470 return {};
1471
1472 return Pos->second;
1473}
1474
1475void
1478 SourceLocation PointOfInstantiation) {
1479 assert(Inst->isStaticDataMember() && "Not a static data member");
1480 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1482 Tmpl, TSK, PointOfInstantiation));
1483}
1484
1485void
1488 assert(!TemplateOrInstantiation[Inst] &&
1489 "Already noted what the variable was instantiated from");
1490 TemplateOrInstantiation[Inst] = TSI;
1491}
1492
1493NamedDecl *
1495 return InstantiatedFromUsingDecl.lookup(UUD);
1496}
1497
1498void
1500 assert((isa<UsingDecl>(Pattern) ||
1503 "pattern decl is not a using decl");
1504 assert((isa<UsingDecl>(Inst) ||
1507 "instantiation did not produce a using decl");
1508 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1509 InstantiatedFromUsingDecl[Inst] = Pattern;
1510}
1511
1514 return InstantiatedFromUsingEnumDecl.lookup(UUD);
1515}
1516
1518 UsingEnumDecl *Pattern) {
1519 assert(!InstantiatedFromUsingEnumDecl[Inst] && "pattern already exists");
1520 InstantiatedFromUsingEnumDecl[Inst] = Pattern;
1521}
1522
1525 return InstantiatedFromUsingShadowDecl.lookup(Inst);
1526}
1527
1528void
1530 UsingShadowDecl *Pattern) {
1531 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1532 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1533}
1534
1535FieldDecl *
1537 return InstantiatedFromUnnamedFieldDecl.lookup(Field);
1538}
1539
1541 FieldDecl *Tmpl) {
1542 assert((!Inst->getDeclName() || Inst->isPlaceholderVar(getLangOpts())) &&
1543 "Instantiated field decl is not unnamed");
1544 assert((!Inst->getDeclName() || Inst->isPlaceholderVar(getLangOpts())) &&
1545 "Template field decl is not unnamed");
1546 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1547 "Already noted what unnamed field was instantiated from");
1548
1549 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1550}
1551
1556
1561
1562unsigned
1564 auto Range = overridden_methods(Method);
1565 return Range.end() - Range.begin();
1566}
1567
1570 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1571 OverriddenMethods.find(Method->getCanonicalDecl());
1572 if (Pos == OverriddenMethods.end())
1573 return overridden_method_range(nullptr, nullptr);
1574 return overridden_method_range(Pos->second.begin(), Pos->second.end());
1575}
1576
1578 const CXXMethodDecl *Overridden) {
1579 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1580 OverriddenMethods[Method].push_back(Overridden);
1581}
1582
1584 const NamedDecl *D,
1585 SmallVectorImpl<const NamedDecl *> &Overridden) const {
1586 assert(D);
1587
1588 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1589 Overridden.append(overridden_methods_begin(CXXMethod),
1590 overridden_methods_end(CXXMethod));
1591 return;
1592 }
1593
1594 const auto *Method = dyn_cast<ObjCMethodDecl>(D);
1595 if (!Method)
1596 return;
1597
1599 Method->getOverriddenMethods(OverDecls);
1600 Overridden.append(OverDecls.begin(), OverDecls.end());
1601}
1602
1603std::optional<ASTContext::CXXRecordDeclRelocationInfo>
1605 assert(RD);
1606 CXXRecordDecl *D = RD->getDefinition();
1607 auto it = RelocatableClasses.find(D);
1608 if (it != RelocatableClasses.end())
1609 return it->getSecond();
1610 return std::nullopt;
1611}
1612
1615 assert(RD);
1616 CXXRecordDecl *D = RD->getDefinition();
1617 assert(RelocatableClasses.find(D) == RelocatableClasses.end());
1618 RelocatableClasses.insert({D, Info});
1619}
1620
1622 const ASTContext &Context, const CXXRecordDecl *Class) {
1623 if (!Class->isPolymorphic())
1624 return false;
1625 const CXXRecordDecl *BaseType = Context.baseForVTableAuthentication(Class);
1626 using AuthAttr = VTablePointerAuthenticationAttr;
1627 const AuthAttr *ExplicitAuth = BaseType->getAttr<AuthAttr>();
1628 if (!ExplicitAuth)
1629 return Context.getLangOpts().PointerAuthVTPtrAddressDiscrimination;
1630 AuthAttr::AddressDiscriminationMode AddressDiscrimination =
1631 ExplicitAuth->getAddressDiscrimination();
1632 if (AddressDiscrimination == AuthAttr::DefaultAddressDiscrimination)
1633 return Context.getLangOpts().PointerAuthVTPtrAddressDiscrimination;
1634 return AddressDiscrimination == AuthAttr::AddressDiscrimination;
1635}
1636
1637ASTContext::PointerAuthContent
1638ASTContext::findPointerAuthContent(QualType T) const {
1639 assert(isPointerAuthenticationAvailable());
1640
1641 T = T.getCanonicalType();
1642 if (T->isDependentType())
1643 return PointerAuthContent::None;
1644
1645 if (T.hasAddressDiscriminatedPointerAuth())
1646 return PointerAuthContent::AddressDiscriminatedData;
1647 const RecordDecl *RD = T->getAsRecordDecl();
1648 if (!RD)
1649 return PointerAuthContent::None;
1650
1651 if (auto Existing = RecordContainsAddressDiscriminatedPointerAuth.find(RD);
1652 Existing != RecordContainsAddressDiscriminatedPointerAuth.end())
1653 return Existing->second;
1654
1655 PointerAuthContent Result = PointerAuthContent::None;
1656
1657 auto SaveResultAndReturn = [&]() -> PointerAuthContent {
1658 auto [ResultIter, DidAdd] =
1659 RecordContainsAddressDiscriminatedPointerAuth.try_emplace(RD, Result);
1660 (void)ResultIter;
1661 (void)DidAdd;
1662 assert(DidAdd);
1663 return Result;
1664 };
1665 auto ShouldContinueAfterUpdate = [&](PointerAuthContent NewResult) {
1666 static_assert(PointerAuthContent::None <
1667 PointerAuthContent::AddressDiscriminatedVTable);
1668 static_assert(PointerAuthContent::AddressDiscriminatedVTable <
1669 PointerAuthContent::AddressDiscriminatedData);
1670 if (NewResult > Result)
1671 Result = NewResult;
1672 return Result != PointerAuthContent::AddressDiscriminatedData;
1673 };
1674 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1676 !ShouldContinueAfterUpdate(
1677 PointerAuthContent::AddressDiscriminatedVTable))
1678 return SaveResultAndReturn();
1679 for (auto Base : CXXRD->bases()) {
1680 if (!ShouldContinueAfterUpdate(findPointerAuthContent(Base.getType())))
1681 return SaveResultAndReturn();
1682 }
1683 }
1684 for (auto *FieldDecl : RD->fields()) {
1685 if (!ShouldContinueAfterUpdate(
1686 findPointerAuthContent(FieldDecl->getType())))
1687 return SaveResultAndReturn();
1688 }
1689 return SaveResultAndReturn();
1690}
1691
1693 assert(!Import->getNextLocalImport() &&
1694 "Import declaration already in the chain");
1695 assert(!Import->isFromASTFile() && "Non-local import declaration");
1696 if (!FirstLocalImport) {
1697 FirstLocalImport = Import;
1698 LastLocalImport = Import;
1699 return;
1700 }
1701
1702 LastLocalImport->setNextLocalImport(Import);
1703 LastLocalImport = Import;
1704}
1705
1706//===----------------------------------------------------------------------===//
1707// Type Sizing and Analysis
1708//===----------------------------------------------------------------------===//
1709
1710/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1711/// scalar floating point type.
1712const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1713 switch (T->castAs<BuiltinType>()->getKind()) {
1714 default:
1715 llvm_unreachable("Not a floating point type!");
1716 case BuiltinType::BFloat16:
1717 return Target->getBFloat16Format();
1718 case BuiltinType::Float16:
1719 return Target->getHalfFormat();
1720 case BuiltinType::Half:
1721 return Target->getHalfFormat();
1722 case BuiltinType::Float: return Target->getFloatFormat();
1723 case BuiltinType::Double: return Target->getDoubleFormat();
1724 case BuiltinType::Ibm128:
1725 return Target->getIbm128Format();
1726 case BuiltinType::LongDouble:
1727 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1728 return AuxTarget->getLongDoubleFormat();
1729 return Target->getLongDoubleFormat();
1730 case BuiltinType::Float128:
1731 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1732 return AuxTarget->getFloat128Format();
1733 return Target->getFloat128Format();
1734 }
1735}
1736
1737CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1738 unsigned Align = Target->getCharWidth();
1739
1740 const unsigned AlignFromAttr = D->getMaxAlignment();
1741 if (AlignFromAttr)
1742 Align = AlignFromAttr;
1743
1744 // __attribute__((aligned)) can increase or decrease alignment
1745 // *except* on a struct or struct member, where it only increases
1746 // alignment unless 'packed' is also specified.
1747 //
1748 // It is an error for alignas to decrease alignment, so we can
1749 // ignore that possibility; Sema should diagnose it.
1750 bool UseAlignAttrOnly;
1751 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D))
1752 UseAlignAttrOnly =
1753 FD->hasAttr<PackedAttr>() || FD->getParent()->hasAttr<PackedAttr>();
1754 else
1755 UseAlignAttrOnly = AlignFromAttr != 0;
1756 // If we're using the align attribute only, just ignore everything
1757 // else about the declaration and its type.
1758 if (UseAlignAttrOnly) {
1759 // do nothing
1760 } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
1761 QualType T = VD->getType();
1762 if (const auto *RT = T->getAs<ReferenceType>()) {
1763 if (ForAlignof)
1764 T = RT->getPointeeType();
1765 else
1766 T = getPointerType(RT->getPointeeType());
1767 }
1768 QualType BaseT = getBaseElementType(T);
1769 if (T->isFunctionType())
1770 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1771 else if (!BaseT->isIncompleteType()) {
1772 // Adjust alignments of declarations with array type by the
1773 // large-array alignment on the target.
1774 if (const ArrayType *arrayType = getAsArrayType(T)) {
1775 unsigned MinWidth = Target->getLargeArrayMinWidth();
1776 if (!ForAlignof && MinWidth) {
1778 Align = std::max(Align, Target->getLargeArrayAlign());
1781 Align = std::max(Align, Target->getLargeArrayAlign());
1782 }
1783 }
1784 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1785 if (BaseT.getQualifiers().hasUnaligned())
1786 Align = Target->getCharWidth();
1787 }
1788
1789 // Ensure minimum alignment for global variables.
1790 if (const auto *VD = dyn_cast<VarDecl>(D))
1791 if (VD->hasGlobalStorage() && !ForAlignof) {
1792 uint64_t TypeSize =
1793 !BaseT->isIncompleteType() ? getTypeSize(T.getTypePtr()) : 0;
1794 Align = std::max(Align, getMinGlobalAlignOfVar(TypeSize, VD));
1795 }
1796
1797 // Fields can be subject to extra alignment constraints, like if
1798 // the field is packed, the struct is packed, or the struct has a
1799 // a max-field-alignment constraint (#pragma pack). So calculate
1800 // the actual alignment of the field within the struct, and then
1801 // (as we're expected to) constrain that by the alignment of the type.
1802 if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
1803 const RecordDecl *Parent = Field->getParent();
1804 // We can only produce a sensible answer if the record is valid.
1805 if (!Parent->isInvalidDecl()) {
1806 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
1807
1808 // Start with the record's overall alignment.
1809 unsigned FieldAlign = toBits(Layout.getAlignment());
1810
1811 // Use the GCD of that and the offset within the record.
1812 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1813 if (Offset > 0) {
1814 // Alignment is always a power of 2, so the GCD will be a power of 2,
1815 // which means we get to do this crazy thing instead of Euclid's.
1816 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1817 if (LowBitOfOffset < FieldAlign)
1818 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1819 }
1820
1821 Align = std::min(Align, FieldAlign);
1822 }
1823 }
1824 }
1825
1826 // Some targets have hard limitation on the maximum requestable alignment in
1827 // aligned attribute for static variables.
1828 const unsigned MaxAlignedAttr = getTargetInfo().getMaxAlignedAttribute();
1829 const auto *VD = dyn_cast<VarDecl>(D);
1830 if (MaxAlignedAttr && VD && VD->getStorageClass() == SC_Static)
1831 Align = std::min(Align, MaxAlignedAttr);
1832
1833 return toCharUnitsFromBits(Align);
1834}
1835
1837 return toCharUnitsFromBits(Target->getExnObjectAlignment());
1838}
1839
1840// getTypeInfoDataSizeInChars - Return the size of a type, in
1841// chars. If the type is a record, its data size is returned. This is
1842// the size of the memcpy that's performed when assigning this type
1843// using a trivial copy/move assignment operator.
1846
1847 // In C++, objects can sometimes be allocated into the tail padding
1848 // of a base-class subobject. We decide whether that's possible
1849 // during class layout, so here we can just trust the layout results.
1850 if (getLangOpts().CPlusPlus) {
1851 if (const auto *RD = T->getAsCXXRecordDecl(); RD && !RD->isInvalidDecl()) {
1852 const ASTRecordLayout &layout = getASTRecordLayout(RD);
1853 Info.Width = layout.getDataSize();
1854 }
1855 }
1856
1857 return Info;
1858}
1859
1860/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1861/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1864 const ConstantArrayType *CAT) {
1865 TypeInfoChars EltInfo = Context.getTypeInfoInChars(CAT->getElementType());
1866 uint64_t Size = CAT->getZExtSize();
1867 assert((Size == 0 || static_cast<uint64_t>(EltInfo.Width.getQuantity()) <=
1868 (uint64_t)(-1)/Size) &&
1869 "Overflow in array type char size evaluation");
1870 uint64_t Width = EltInfo.Width.getQuantity() * Size;
1871 unsigned Align = EltInfo.Align.getQuantity();
1872 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1873 Context.getTargetInfo().getPointerWidth(LangAS::Default) == 64)
1874 Width = llvm::alignTo(Width, Align);
1877 EltInfo.AlignRequirement);
1878}
1879
1881 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
1882 return getConstantArrayInfoInChars(*this, CAT);
1883 TypeInfo Info = getTypeInfo(T);
1886}
1887
1891
1893 // HLSL doesn't promote all small integer types to int, it
1894 // just uses the rank-based promotion rules for all types.
1895 if (getLangOpts().HLSL)
1896 return false;
1897
1898 if (const auto *BT = T->getAs<BuiltinType>())
1899 switch (BT->getKind()) {
1900 case BuiltinType::Bool:
1901 case BuiltinType::Char_S:
1902 case BuiltinType::Char_U:
1903 case BuiltinType::SChar:
1904 case BuiltinType::UChar:
1905 case BuiltinType::Short:
1906 case BuiltinType::UShort:
1907 case BuiltinType::WChar_S:
1908 case BuiltinType::WChar_U:
1909 case BuiltinType::Char8:
1910 case BuiltinType::Char16:
1911 case BuiltinType::Char32:
1912 return true;
1913 default:
1914 return false;
1915 }
1916
1917 // Enumerated types are promotable to their compatible integer types
1918 // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
1919 if (const auto *ED = T->getAsEnumDecl()) {
1920 if (T->isDependentType() || ED->getPromotionType().isNull() ||
1921 ED->isScoped())
1922 return false;
1923
1924 return true;
1925 }
1926
1927 return false;
1928}
1929
1933
1935 return isAlignmentRequired(T.getTypePtr());
1936}
1937
1939 bool NeedsPreferredAlignment) const {
1940 // An alignment on a typedef overrides anything else.
1941 if (const auto *TT = T->getAs<TypedefType>())
1942 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1943 return Align;
1944
1945 // If we have an (array of) complete type, we're done.
1947 if (!T->isIncompleteType())
1948 return NeedsPreferredAlignment ? getPreferredTypeAlign(T) : getTypeAlign(T);
1949
1950 // If we had an array type, its element type might be a typedef
1951 // type with an alignment attribute.
1952 if (const auto *TT = T->getAs<TypedefType>())
1953 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1954 return Align;
1955
1956 // Otherwise, see if the declaration of the type had an attribute.
1957 if (const auto *TD = T->getAsTagDecl())
1958 return TD->getMaxAlignment();
1959
1960 return 0;
1961}
1962
1964 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1965 if (I != MemoizedTypeInfo.end())
1966 return I->second;
1967
1968 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1969 TypeInfo TI = getTypeInfoImpl(T);
1970 MemoizedTypeInfo[T] = TI;
1971 return TI;
1972}
1973
1974/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1975/// method does not work on incomplete types.
1976///
1977/// FIXME: Pointers into different addr spaces could have different sizes and
1978/// alignment requirements: getPointerInfo should take an AddrSpace, this
1979/// should take a QualType, &c.
1980TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1981 uint64_t Width = 0;
1982 unsigned Align = 8;
1985 switch (T->getTypeClass()) {
1986#define TYPE(Class, Base)
1987#define ABSTRACT_TYPE(Class, Base)
1988#define NON_CANONICAL_TYPE(Class, Base)
1989#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1990#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1991 case Type::Class: \
1992 assert(!T->isDependentType() && "should not see dependent types here"); \
1993 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
1994#include "clang/AST/TypeNodes.inc"
1995 llvm_unreachable("Should not see dependent types");
1996
1997 case Type::FunctionNoProto:
1998 case Type::FunctionProto:
1999 // GCC extension: alignof(function) = 32 bits
2000 Width = 0;
2001 Align = 32;
2002 break;
2003
2004 case Type::IncompleteArray:
2005 case Type::VariableArray:
2006 case Type::ConstantArray:
2007 case Type::ArrayParameter: {
2008 // Model non-constant sized arrays as size zero, but track the alignment.
2009 uint64_t Size = 0;
2010 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
2011 Size = CAT->getZExtSize();
2012
2013 TypeInfo EltInfo = getTypeInfo(cast<ArrayType>(T)->getElementType());
2014 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
2015 "Overflow in array type bit size evaluation");
2016 Width = EltInfo.Width * Size;
2017 Align = EltInfo.Align;
2018 AlignRequirement = EltInfo.AlignRequirement;
2019 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
2020 getTargetInfo().getPointerWidth(LangAS::Default) == 64)
2021 Width = llvm::alignTo(Width, Align);
2022 break;
2023 }
2024
2025 case Type::ExtVector:
2026 case Type::Vector: {
2027 const auto *VT = cast<VectorType>(T);
2028 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
2029 Width = VT->isPackedVectorBoolType(*this)
2030 ? VT->getNumElements()
2031 : EltInfo.Width * VT->getNumElements();
2032 // Enforce at least byte size and alignment.
2033 Width = std::max<unsigned>(8, Width);
2034 Align = std::max<unsigned>(8, Width);
2035
2036 // If the alignment is not a power of 2, round up to the next power of 2.
2037 // This happens for non-power-of-2 length vectors.
2038 if (Align & (Align-1)) {
2039 Align = llvm::bit_ceil(Align);
2040 Width = llvm::alignTo(Width, Align);
2041 }
2042 // Adjust the alignment based on the target max.
2043 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
2044 if (TargetVectorAlign && TargetVectorAlign < Align)
2045 Align = TargetVectorAlign;
2046 if (VT->getVectorKind() == VectorKind::SveFixedLengthData)
2047 // Adjust the alignment for fixed-length SVE vectors. This is important
2048 // for non-power-of-2 vector lengths.
2049 Align = 128;
2050 else if (VT->getVectorKind() == VectorKind::SveFixedLengthPredicate)
2051 // Adjust the alignment for fixed-length SVE predicates.
2052 Align = 16;
2053 else if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
2054 VT->getVectorKind() == VectorKind::RVVFixedLengthMask ||
2055 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_1 ||
2056 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_2 ||
2057 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_4)
2058 // Adjust the alignment for fixed-length RVV vectors.
2059 Align = std::min<unsigned>(64, Width);
2060 break;
2061 }
2062
2063 case Type::ConstantMatrix: {
2064 const auto *MT = cast<ConstantMatrixType>(T);
2065 TypeInfo ElementInfo = getTypeInfo(MT->getElementType());
2066 // The internal layout of a matrix value is implementation defined.
2067 // Initially be ABI compatible with arrays with respect to alignment and
2068 // size.
2069 Width = ElementInfo.Width * MT->getNumRows() * MT->getNumColumns();
2070 Align = ElementInfo.Align;
2071 break;
2072 }
2073
2074 case Type::Builtin:
2075 switch (cast<BuiltinType>(T)->getKind()) {
2076 default: llvm_unreachable("Unknown builtin type!");
2077 case BuiltinType::Void:
2078 // GCC extension: alignof(void) = 8 bits.
2079 Width = 0;
2080 Align = 8;
2081 break;
2082 case BuiltinType::Bool:
2083 Width = Target->getBoolWidth();
2084 Align = Target->getBoolAlign();
2085 break;
2086 case BuiltinType::Char_S:
2087 case BuiltinType::Char_U:
2088 case BuiltinType::UChar:
2089 case BuiltinType::SChar:
2090 case BuiltinType::Char8:
2091 Width = Target->getCharWidth();
2092 Align = Target->getCharAlign();
2093 break;
2094 case BuiltinType::WChar_S:
2095 case BuiltinType::WChar_U:
2096 Width = Target->getWCharWidth();
2097 Align = Target->getWCharAlign();
2098 break;
2099 case BuiltinType::Char16:
2100 Width = Target->getChar16Width();
2101 Align = Target->getChar16Align();
2102 break;
2103 case BuiltinType::Char32:
2104 Width = Target->getChar32Width();
2105 Align = Target->getChar32Align();
2106 break;
2107 case BuiltinType::UShort:
2108 case BuiltinType::Short:
2109 Width = Target->getShortWidth();
2110 Align = Target->getShortAlign();
2111 break;
2112 case BuiltinType::UInt:
2113 case BuiltinType::Int:
2114 Width = Target->getIntWidth();
2115 Align = Target->getIntAlign();
2116 break;
2117 case BuiltinType::ULong:
2118 case BuiltinType::Long:
2119 Width = Target->getLongWidth();
2120 Align = Target->getLongAlign();
2121 break;
2122 case BuiltinType::ULongLong:
2123 case BuiltinType::LongLong:
2124 Width = Target->getLongLongWidth();
2125 Align = Target->getLongLongAlign();
2126 break;
2127 case BuiltinType::Int128:
2128 case BuiltinType::UInt128:
2129 Width = 128;
2130 Align = Target->getInt128Align();
2131 break;
2132 case BuiltinType::ShortAccum:
2133 case BuiltinType::UShortAccum:
2134 case BuiltinType::SatShortAccum:
2135 case BuiltinType::SatUShortAccum:
2136 Width = Target->getShortAccumWidth();
2137 Align = Target->getShortAccumAlign();
2138 break;
2139 case BuiltinType::Accum:
2140 case BuiltinType::UAccum:
2141 case BuiltinType::SatAccum:
2142 case BuiltinType::SatUAccum:
2143 Width = Target->getAccumWidth();
2144 Align = Target->getAccumAlign();
2145 break;
2146 case BuiltinType::LongAccum:
2147 case BuiltinType::ULongAccum:
2148 case BuiltinType::SatLongAccum:
2149 case BuiltinType::SatULongAccum:
2150 Width = Target->getLongAccumWidth();
2151 Align = Target->getLongAccumAlign();
2152 break;
2153 case BuiltinType::ShortFract:
2154 case BuiltinType::UShortFract:
2155 case BuiltinType::SatShortFract:
2156 case BuiltinType::SatUShortFract:
2157 Width = Target->getShortFractWidth();
2158 Align = Target->getShortFractAlign();
2159 break;
2160 case BuiltinType::Fract:
2161 case BuiltinType::UFract:
2162 case BuiltinType::SatFract:
2163 case BuiltinType::SatUFract:
2164 Width = Target->getFractWidth();
2165 Align = Target->getFractAlign();
2166 break;
2167 case BuiltinType::LongFract:
2168 case BuiltinType::ULongFract:
2169 case BuiltinType::SatLongFract:
2170 case BuiltinType::SatULongFract:
2171 Width = Target->getLongFractWidth();
2172 Align = Target->getLongFractAlign();
2173 break;
2174 case BuiltinType::BFloat16:
2175 if (Target->hasBFloat16Type()) {
2176 Width = Target->getBFloat16Width();
2177 Align = Target->getBFloat16Align();
2178 } else if ((getLangOpts().SYCLIsDevice ||
2179 (getLangOpts().OpenMP &&
2180 getLangOpts().OpenMPIsTargetDevice)) &&
2181 AuxTarget->hasBFloat16Type()) {
2182 Width = AuxTarget->getBFloat16Width();
2183 Align = AuxTarget->getBFloat16Align();
2184 }
2185 break;
2186 case BuiltinType::Float16:
2187 case BuiltinType::Half:
2188 if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
2189 !getLangOpts().OpenMPIsTargetDevice) {
2190 Width = Target->getHalfWidth();
2191 Align = Target->getHalfAlign();
2192 } else {
2193 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2194 "Expected OpenMP device compilation.");
2195 Width = AuxTarget->getHalfWidth();
2196 Align = AuxTarget->getHalfAlign();
2197 }
2198 break;
2199 case BuiltinType::Float:
2200 Width = Target->getFloatWidth();
2201 Align = Target->getFloatAlign();
2202 break;
2203 case BuiltinType::Double:
2204 Width = Target->getDoubleWidth();
2205 Align = Target->getDoubleAlign();
2206 break;
2207 case BuiltinType::Ibm128:
2208 Width = Target->getIbm128Width();
2209 Align = Target->getIbm128Align();
2210 break;
2211 case BuiltinType::LongDouble:
2212 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2213 (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() ||
2214 Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) {
2215 Width = AuxTarget->getLongDoubleWidth();
2216 Align = AuxTarget->getLongDoubleAlign();
2217 } else {
2218 Width = Target->getLongDoubleWidth();
2219 Align = Target->getLongDoubleAlign();
2220 }
2221 break;
2222 case BuiltinType::Float128:
2223 if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
2224 !getLangOpts().OpenMPIsTargetDevice) {
2225 Width = Target->getFloat128Width();
2226 Align = Target->getFloat128Align();
2227 } else {
2228 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2229 "Expected OpenMP device compilation.");
2230 Width = AuxTarget->getFloat128Width();
2231 Align = AuxTarget->getFloat128Align();
2232 }
2233 break;
2234 case BuiltinType::NullPtr:
2235 // C++ 3.9.1p11: sizeof(nullptr_t) == sizeof(void*)
2236 Width = Target->getPointerWidth(LangAS::Default);
2237 Align = Target->getPointerAlign(LangAS::Default);
2238 break;
2239 case BuiltinType::ObjCId:
2240 case BuiltinType::ObjCClass:
2241 case BuiltinType::ObjCSel:
2242 Width = Target->getPointerWidth(LangAS::Default);
2243 Align = Target->getPointerAlign(LangAS::Default);
2244 break;
2245 case BuiltinType::OCLSampler:
2246 case BuiltinType::OCLEvent:
2247 case BuiltinType::OCLClkEvent:
2248 case BuiltinType::OCLQueue:
2249 case BuiltinType::OCLReserveID:
2250#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2251 case BuiltinType::Id:
2252#include "clang/Basic/OpenCLImageTypes.def"
2253#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2254 case BuiltinType::Id:
2255#include "clang/Basic/OpenCLExtensionTypes.def"
2256 AS = Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
2257 Width = Target->getPointerWidth(AS);
2258 Align = Target->getPointerAlign(AS);
2259 break;
2260 // The SVE types are effectively target-specific. The length of an
2261 // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple
2262 // of 128 bits. There is one predicate bit for each vector byte, so the
2263 // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits.
2264 //
2265 // Because the length is only known at runtime, we use a dummy value
2266 // of 0 for the static length. The alignment values are those defined
2267 // by the Procedure Call Standard for the Arm Architecture.
2268#define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId) \
2269 case BuiltinType::Id: \
2270 Width = 0; \
2271 Align = 128; \
2272 break;
2273#define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId) \
2274 case BuiltinType::Id: \
2275 Width = 0; \
2276 Align = 16; \
2277 break;
2278#define SVE_OPAQUE_TYPE(Name, MangledName, Id, SingletonId) \
2279 case BuiltinType::Id: \
2280 Width = 0; \
2281 Align = 16; \
2282 break;
2283#define SVE_SCALAR_TYPE(Name, MangledName, Id, SingletonId, Bits) \
2284 case BuiltinType::Id: \
2285 Width = Bits; \
2286 Align = Bits; \
2287 break;
2288#include "clang/Basic/AArch64ACLETypes.def"
2289#define PPC_VECTOR_TYPE(Name, Id, Size) \
2290 case BuiltinType::Id: \
2291 Width = Size; \
2292 Align = Size; \
2293 break;
2294#include "clang/Basic/PPCTypes.def"
2295#define RVV_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, NF, IsSigned, \
2296 IsFP, IsBF) \
2297 case BuiltinType::Id: \
2298 Width = 0; \
2299 Align = ElBits; \
2300 break;
2301#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, ElKind) \
2302 case BuiltinType::Id: \
2303 Width = 0; \
2304 Align = 8; \
2305 break;
2306#include "clang/Basic/RISCVVTypes.def"
2307#define WASM_TYPE(Name, Id, SingletonId) \
2308 case BuiltinType::Id: \
2309 Width = 0; \
2310 Align = 8; \
2311 break;
2312#include "clang/Basic/WebAssemblyReferenceTypes.def"
2313#define AMDGPU_TYPE(NAME, ID, SINGLETONID, WIDTH, ALIGN) \
2314 case BuiltinType::ID: \
2315 Width = WIDTH; \
2316 Align = ALIGN; \
2317 break;
2318#include "clang/Basic/AMDGPUTypes.def"
2319#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
2320#include "clang/Basic/HLSLIntangibleTypes.def"
2321 Width = Target->getPointerWidth(LangAS::Default);
2322 Align = Target->getPointerAlign(LangAS::Default);
2323 break;
2324 }
2325 break;
2326 case Type::ObjCObjectPointer:
2327 Width = Target->getPointerWidth(LangAS::Default);
2328 Align = Target->getPointerAlign(LangAS::Default);
2329 break;
2330 case Type::BlockPointer:
2331 AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
2332 Width = Target->getPointerWidth(AS);
2333 Align = Target->getPointerAlign(AS);
2334 break;
2335 case Type::LValueReference:
2336 case Type::RValueReference:
2337 // alignof and sizeof should never enter this code path here, so we go
2338 // the pointer route.
2339 AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
2340 Width = Target->getPointerWidth(AS);
2341 Align = Target->getPointerAlign(AS);
2342 break;
2343 case Type::Pointer:
2344 AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
2345 Width = Target->getPointerWidth(AS);
2346 Align = Target->getPointerAlign(AS);
2347 break;
2348 case Type::MemberPointer: {
2349 const auto *MPT = cast<MemberPointerType>(T);
2350 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
2351 Width = MPI.Width;
2352 Align = MPI.Align;
2353 break;
2354 }
2355 case Type::Complex: {
2356 // Complex types have the same alignment as their elements, but twice the
2357 // size.
2358 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
2359 Width = EltInfo.Width * 2;
2360 Align = EltInfo.Align;
2361 break;
2362 }
2363 case Type::ObjCObject:
2364 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
2365 case Type::Adjusted:
2366 case Type::Decayed:
2367 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
2368 case Type::ObjCInterface: {
2369 const auto *ObjCI = cast<ObjCInterfaceType>(T);
2370 if (ObjCI->getDecl()->isInvalidDecl()) {
2371 Width = 8;
2372 Align = 8;
2373 break;
2374 }
2375 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2376 Width = toBits(Layout.getSize());
2377 Align = toBits(Layout.getAlignment());
2378 break;
2379 }
2380 case Type::BitInt: {
2381 const auto *EIT = cast<BitIntType>(T);
2382 Align = Target->getBitIntAlign(EIT->getNumBits());
2383 Width = Target->getBitIntWidth(EIT->getNumBits());
2384 break;
2385 }
2386 case Type::Record:
2387 case Type::Enum: {
2388 const auto *TT = cast<TagType>(T);
2389 const TagDecl *TD = TT->getDecl()->getDefinitionOrSelf();
2390
2391 if (TD->isInvalidDecl()) {
2392 Width = 8;
2393 Align = 8;
2394 break;
2395 }
2396
2397 if (isa<EnumType>(TT)) {
2398 const EnumDecl *ED = cast<EnumDecl>(TD);
2399 TypeInfo Info =
2401 if (unsigned AttrAlign = ED->getMaxAlignment()) {
2402 Info.Align = AttrAlign;
2404 }
2405 return Info;
2406 }
2407
2408 const auto *RD = cast<RecordDecl>(TD);
2409 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2410 Width = toBits(Layout.getSize());
2411 Align = toBits(Layout.getAlignment());
2412 AlignRequirement = RD->hasAttr<AlignedAttr>()
2414 : AlignRequirementKind::None;
2415 break;
2416 }
2417
2418 case Type::SubstTemplateTypeParm:
2420 getReplacementType().getTypePtr());
2421
2422 case Type::Auto:
2423 case Type::DeducedTemplateSpecialization: {
2424 const auto *A = cast<DeducedType>(T);
2425 assert(!A->getDeducedType().isNull() &&
2426 "cannot request the size of an undeduced or dependent auto type");
2427 return getTypeInfo(A->getDeducedType().getTypePtr());
2428 }
2429
2430 case Type::Paren:
2431 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
2432
2433 case Type::MacroQualified:
2434 return getTypeInfo(
2436
2437 case Type::ObjCTypeParam:
2438 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
2439
2440 case Type::Using:
2441 return getTypeInfo(cast<UsingType>(T)->desugar().getTypePtr());
2442
2443 case Type::Typedef: {
2444 const auto *TT = cast<TypedefType>(T);
2445 TypeInfo Info = getTypeInfo(TT->desugar().getTypePtr());
2446 // If the typedef has an aligned attribute on it, it overrides any computed
2447 // alignment we have. This violates the GCC documentation (which says that
2448 // attribute(aligned) can only round up) but matches its implementation.
2449 if (unsigned AttrAlign = TT->getDecl()->getMaxAlignment()) {
2450 Align = AttrAlign;
2451 AlignRequirement = AlignRequirementKind::RequiredByTypedef;
2452 } else {
2453 Align = Info.Align;
2454 AlignRequirement = Info.AlignRequirement;
2455 }
2456 Width = Info.Width;
2457 break;
2458 }
2459
2460 case Type::Attributed:
2461 return getTypeInfo(
2462 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
2463
2464 case Type::CountAttributed:
2465 return getTypeInfo(cast<CountAttributedType>(T)->desugar().getTypePtr());
2466
2467 case Type::BTFTagAttributed:
2468 return getTypeInfo(
2469 cast<BTFTagAttributedType>(T)->getWrappedType().getTypePtr());
2470
2471 case Type::HLSLAttributedResource:
2472 return getTypeInfo(
2473 cast<HLSLAttributedResourceType>(T)->getWrappedType().getTypePtr());
2474
2475 case Type::HLSLInlineSpirv: {
2476 const auto *ST = cast<HLSLInlineSpirvType>(T);
2477 // Size is specified in bytes, convert to bits
2478 Width = ST->getSize() * 8;
2479 Align = ST->getAlignment();
2480 if (Width == 0 && Align == 0) {
2481 // We are defaulting to laying out opaque SPIR-V types as 32-bit ints.
2482 Width = 32;
2483 Align = 32;
2484 }
2485 break;
2486 }
2487
2488 case Type::Atomic: {
2489 // Start with the base type information.
2490 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
2491 Width = Info.Width;
2492 Align = Info.Align;
2493
2494 if (!Width) {
2495 // An otherwise zero-sized type should still generate an
2496 // atomic operation.
2497 Width = Target->getCharWidth();
2498 assert(Align);
2499 } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2500 // If the size of the type doesn't exceed the platform's max
2501 // atomic promotion width, make the size and alignment more
2502 // favorable to atomic operations:
2503
2504 // Round the size up to a power of 2.
2505 Width = llvm::bit_ceil(Width);
2506
2507 // Set the alignment equal to the size.
2508 Align = static_cast<unsigned>(Width);
2509 }
2510 }
2511 break;
2512
2513 case Type::PredefinedSugar:
2514 return getTypeInfo(cast<PredefinedSugarType>(T)->desugar().getTypePtr());
2515
2516 case Type::Pipe:
2517 Width = Target->getPointerWidth(LangAS::opencl_global);
2518 Align = Target->getPointerAlign(LangAS::opencl_global);
2519 break;
2520 }
2521
2522 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
2523 return TypeInfo(Width, Align, AlignRequirement);
2524}
2525
2527 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
2528 if (I != MemoizedUnadjustedAlign.end())
2529 return I->second;
2530
2531 unsigned UnadjustedAlign;
2532 if (const auto *RT = T->getAsCanonical<RecordType>()) {
2533 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
2534 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2535 } else if (const auto *ObjCI = T->getAsCanonical<ObjCInterfaceType>()) {
2536 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2537 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2538 } else {
2539 UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType());
2540 }
2541
2542 MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2543 return UnadjustedAlign;
2544}
2545
2547 unsigned SimdAlign = llvm::OpenMPIRBuilder::getOpenMPDefaultSimdAlign(
2548 getTargetInfo().getTriple(), Target->getTargetOpts().FeatureMap);
2549 return SimdAlign;
2550}
2551
2552/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2554 return CharUnits::fromQuantity(BitSize / getCharWidth());
2555}
2556
2557/// toBits - Convert a size in characters to a size in characters.
2558int64_t ASTContext::toBits(CharUnits CharSize) const {
2559 return CharSize.getQuantity() * getCharWidth();
2560}
2561
2562/// getTypeSizeInChars - Return the size of the specified type, in characters.
2563/// This method does not work on incomplete types.
2570
2571/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
2572/// characters. This method does not work on incomplete types.
2579
2580/// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2581/// type, in characters, before alignment adjustments. This method does
2582/// not work on incomplete types.
2589
2590/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2591/// type for the current target in bits. This can be different than the ABI
2592/// alignment in cases where it is beneficial for performance or backwards
2593/// compatibility preserving to overalign a data type. (Note: despite the name,
2594/// the preferred alignment is ABI-impacting, and not an optimization.)
2596 TypeInfo TI = getTypeInfo(T);
2597 unsigned ABIAlign = TI.Align;
2598
2599 T = T->getBaseElementTypeUnsafe();
2600
2601 // The preferred alignment of member pointers is that of a pointer.
2602 if (T->isMemberPointerType())
2603 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2604
2605 if (!Target->allowsLargerPreferedTypeAlignment())
2606 return ABIAlign;
2607
2608 if (const auto *RD = T->getAsRecordDecl()) {
2609 // When used as part of a typedef, or together with a 'packed' attribute,
2610 // the 'aligned' attribute can be used to decrease alignment. Note that the
2611 // 'packed' case is already taken into consideration when computing the
2612 // alignment, we only need to handle the typedef case here.
2614 RD->isInvalidDecl())
2615 return ABIAlign;
2616
2617 unsigned PreferredAlign = static_cast<unsigned>(
2618 toBits(getASTRecordLayout(RD).PreferredAlignment));
2619 assert(PreferredAlign >= ABIAlign &&
2620 "PreferredAlign should be at least as large as ABIAlign.");
2621 return PreferredAlign;
2622 }
2623
2624 // Double (and, for targets supporting AIX `power` alignment, long double) and
2625 // long long should be naturally aligned (despite requiring less alignment) if
2626 // possible.
2627 if (const auto *CT = T->getAs<ComplexType>())
2628 T = CT->getElementType().getTypePtr();
2629 if (const auto *ED = T->getAsEnumDecl())
2630 T = ED->getIntegerType().getTypePtr();
2631 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
2632 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2633 T->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2634 (T->isSpecificBuiltinType(BuiltinType::LongDouble) &&
2635 Target->defaultsToAIXPowerAlignment()))
2636 // Don't increase the alignment if an alignment attribute was specified on a
2637 // typedef declaration.
2638 if (!TI.isAlignRequired())
2639 return std::max(ABIAlign, (unsigned)getTypeSize(T));
2640
2641 return ABIAlign;
2642}
2643
2644/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2645/// for __attribute__((aligned)) on this target, to be used if no alignment
2646/// value is specified.
2650
2651/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2652/// to a global variable of the specified type.
2654 uint64_t TypeSize = getTypeSize(T.getTypePtr());
2655 return std::max(getPreferredTypeAlign(T),
2656 getMinGlobalAlignOfVar(TypeSize, VD));
2657}
2658
2659/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2660/// should be given to a global variable of the specified type.
2665
2667 const VarDecl *VD) const {
2668 // Make the default handling as that of a non-weak definition in the
2669 // current translation unit.
2670 bool HasNonWeakDef = !VD || (VD->hasDefinition() && !VD->isWeak());
2671 return getTargetInfo().getMinGlobalAlign(Size, HasNonWeakDef);
2672}
2673
2675 CharUnits Offset = CharUnits::Zero();
2676 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2677 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2678 Offset += Layout->getBaseClassOffset(Base);
2679 Layout = &getASTRecordLayout(Base);
2680 }
2681 return Offset;
2682}
2683
2685 const ValueDecl *MPD = MP.getMemberPointerDecl();
2688 bool DerivedMember = MP.isMemberPointerToDerivedMember();
2690 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
2691 const CXXRecordDecl *Base = RD;
2692 const CXXRecordDecl *Derived = Path[I];
2693 if (DerivedMember)
2694 std::swap(Base, Derived);
2696 RD = Path[I];
2697 }
2698 if (DerivedMember)
2700 return ThisAdjustment;
2701}
2702
2703/// DeepCollectObjCIvars -
2704/// This routine first collects all declared, but not synthesized, ivars in
2705/// super class and then collects all ivars, including those synthesized for
2706/// current class. This routine is used for implementation of current class
2707/// when all ivars, declared and synthesized are known.
2709 bool leafClass,
2711 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2712 DeepCollectObjCIvars(SuperClass, false, Ivars);
2713 if (!leafClass) {
2714 llvm::append_range(Ivars, OI->ivars());
2715 } else {
2716 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
2717 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
2718 Iv= Iv->getNextIvar())
2719 Ivars.push_back(Iv);
2720 }
2721}
2722
2723/// CollectInheritedProtocols - Collect all protocols in current class and
2724/// those inherited by it.
2727 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2728 // We can use protocol_iterator here instead of
2729 // all_referenced_protocol_iterator since we are walking all categories.
2730 for (auto *Proto : OI->all_referenced_protocols()) {
2731 CollectInheritedProtocols(Proto, Protocols);
2732 }
2733
2734 // Categories of this Interface.
2735 for (const auto *Cat : OI->visible_categories())
2736 CollectInheritedProtocols(Cat, Protocols);
2737
2738 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2739 while (SD) {
2740 CollectInheritedProtocols(SD, Protocols);
2741 SD = SD->getSuperClass();
2742 }
2743 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
2744 for (auto *Proto : OC->protocols()) {
2745 CollectInheritedProtocols(Proto, Protocols);
2746 }
2747 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
2748 // Insert the protocol.
2749 if (!Protocols.insert(
2750 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2751 return;
2752
2753 for (auto *Proto : OP->protocols())
2754 CollectInheritedProtocols(Proto, Protocols);
2755 }
2756}
2757
2759 const RecordDecl *RD,
2760 bool CheckIfTriviallyCopyable) {
2761 assert(RD->isUnion() && "Must be union type");
2762 CharUnits UnionSize =
2763 Context.getTypeSizeInChars(Context.getCanonicalTagType(RD));
2764
2765 for (const auto *Field : RD->fields()) {
2766 if (!Context.hasUniqueObjectRepresentations(Field->getType(),
2767 CheckIfTriviallyCopyable))
2768 return false;
2769 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2770 if (FieldSize != UnionSize)
2771 return false;
2772 }
2773 return !RD->field_empty();
2774}
2775
2776static int64_t getSubobjectOffset(const FieldDecl *Field,
2777 const ASTContext &Context,
2778 const clang::ASTRecordLayout & /*Layout*/) {
2779 return Context.getFieldOffset(Field);
2780}
2781
2782static int64_t getSubobjectOffset(const CXXRecordDecl *RD,
2783 const ASTContext &Context,
2784 const clang::ASTRecordLayout &Layout) {
2785 return Context.toBits(Layout.getBaseClassOffset(RD));
2786}
2787
2788static std::optional<int64_t>
2790 const RecordDecl *RD,
2791 bool CheckIfTriviallyCopyable);
2792
2793static std::optional<int64_t>
2794getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context,
2795 bool CheckIfTriviallyCopyable) {
2796 if (const auto *RD = Field->getType()->getAsRecordDecl();
2797 RD && !RD->isUnion())
2798 return structHasUniqueObjectRepresentations(Context, RD,
2799 CheckIfTriviallyCopyable);
2800
2801 // A _BitInt type may not be unique if it has padding bits
2802 // but if it is a bitfield the padding bits are not used.
2803 bool IsBitIntType = Field->getType()->isBitIntType();
2804 if (!Field->getType()->isReferenceType() && !IsBitIntType &&
2805 !Context.hasUniqueObjectRepresentations(Field->getType(),
2806 CheckIfTriviallyCopyable))
2807 return std::nullopt;
2808
2809 int64_t FieldSizeInBits =
2810 Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2811 if (Field->isBitField()) {
2812 // If we have explicit padding bits, they don't contribute bits
2813 // to the actual object representation, so return 0.
2814 if (Field->isUnnamedBitField())
2815 return 0;
2816
2817 int64_t BitfieldSize = Field->getBitWidthValue();
2818 if (IsBitIntType) {
2819 if ((unsigned)BitfieldSize >
2820 cast<BitIntType>(Field->getType())->getNumBits())
2821 return std::nullopt;
2822 } else if (BitfieldSize > FieldSizeInBits) {
2823 return std::nullopt;
2824 }
2825 FieldSizeInBits = BitfieldSize;
2826 } else if (IsBitIntType && !Context.hasUniqueObjectRepresentations(
2827 Field->getType(), CheckIfTriviallyCopyable)) {
2828 return std::nullopt;
2829 }
2830 return FieldSizeInBits;
2831}
2832
2833static std::optional<int64_t>
2835 bool CheckIfTriviallyCopyable) {
2836 return structHasUniqueObjectRepresentations(Context, RD,
2837 CheckIfTriviallyCopyable);
2838}
2839
2840template <typename RangeT>
2842 const RangeT &Subobjects, int64_t CurOffsetInBits,
2843 const ASTContext &Context, const clang::ASTRecordLayout &Layout,
2844 bool CheckIfTriviallyCopyable) {
2845 for (const auto *Subobject : Subobjects) {
2846 std::optional<int64_t> SizeInBits =
2847 getSubobjectSizeInBits(Subobject, Context, CheckIfTriviallyCopyable);
2848 if (!SizeInBits)
2849 return std::nullopt;
2850 if (*SizeInBits != 0) {
2851 int64_t Offset = getSubobjectOffset(Subobject, Context, Layout);
2852 if (Offset != CurOffsetInBits)
2853 return std::nullopt;
2854 CurOffsetInBits += *SizeInBits;
2855 }
2856 }
2857 return CurOffsetInBits;
2858}
2859
2860static std::optional<int64_t>
2862 const RecordDecl *RD,
2863 bool CheckIfTriviallyCopyable) {
2864 assert(!RD->isUnion() && "Must be struct/class type");
2865 const auto &Layout = Context.getASTRecordLayout(RD);
2866
2867 int64_t CurOffsetInBits = 0;
2868 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
2869 if (ClassDecl->isDynamicClass())
2870 return std::nullopt;
2871
2873 for (const auto &Base : ClassDecl->bases()) {
2874 // Empty types can be inherited from, and non-empty types can potentially
2875 // have tail padding, so just make sure there isn't an error.
2876 Bases.emplace_back(Base.getType()->getAsCXXRecordDecl());
2877 }
2878
2879 llvm::sort(Bases, [&](const CXXRecordDecl *L, const CXXRecordDecl *R) {
2880 return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R);
2881 });
2882
2883 std::optional<int64_t> OffsetAfterBases =
2885 Bases, CurOffsetInBits, Context, Layout, CheckIfTriviallyCopyable);
2886 if (!OffsetAfterBases)
2887 return std::nullopt;
2888 CurOffsetInBits = *OffsetAfterBases;
2889 }
2890
2891 std::optional<int64_t> OffsetAfterFields =
2893 RD->fields(), CurOffsetInBits, Context, Layout,
2894 CheckIfTriviallyCopyable);
2895 if (!OffsetAfterFields)
2896 return std::nullopt;
2897 CurOffsetInBits = *OffsetAfterFields;
2898
2899 return CurOffsetInBits;
2900}
2901
2903 QualType Ty, bool CheckIfTriviallyCopyable) const {
2904 // C++17 [meta.unary.prop]:
2905 // The predicate condition for a template specialization
2906 // has_unique_object_representations<T> shall be satisfied if and only if:
2907 // (9.1) - T is trivially copyable, and
2908 // (9.2) - any two objects of type T with the same value have the same
2909 // object representation, where:
2910 // - two objects of array or non-union class type are considered to have
2911 // the same value if their respective sequences of direct subobjects
2912 // have the same values, and
2913 // - two objects of union type are considered to have the same value if
2914 // they have the same active member and the corresponding members have
2915 // the same value.
2916 // The set of scalar types for which this condition holds is
2917 // implementation-defined. [ Note: If a type has padding bits, the condition
2918 // does not hold; otherwise, the condition holds true for unsigned integral
2919 // types. -- end note ]
2920 assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
2921
2922 // Arrays are unique only if their element type is unique.
2923 if (Ty->isArrayType())
2925 CheckIfTriviallyCopyable);
2926
2927 assert((Ty->isVoidType() || !Ty->isIncompleteType()) &&
2928 "hasUniqueObjectRepresentations should not be called with an "
2929 "incomplete type");
2930
2931 // (9.1) - T is trivially copyable...
2932 if (CheckIfTriviallyCopyable && !Ty.isTriviallyCopyableType(*this))
2933 return false;
2934
2935 // All integrals and enums are unique.
2936 if (Ty->isIntegralOrEnumerationType()) {
2937 // Address discriminated integer types are not unique.
2939 return false;
2940 // Except _BitInt types that have padding bits.
2941 if (const auto *BIT = Ty->getAs<BitIntType>())
2942 return getTypeSize(BIT) == BIT->getNumBits();
2943
2944 return true;
2945 }
2946
2947 // All other pointers are unique.
2948 if (Ty->isPointerType())
2950
2951 if (const auto *MPT = Ty->getAs<MemberPointerType>())
2952 return !ABI->getMemberPointerInfo(MPT).HasPadding;
2953
2954 if (const auto *Record = Ty->getAsRecordDecl()) {
2955 if (Record->isInvalidDecl())
2956 return false;
2957
2958 if (Record->isUnion())
2960 CheckIfTriviallyCopyable);
2961
2962 std::optional<int64_t> StructSize = structHasUniqueObjectRepresentations(
2963 *this, Record, CheckIfTriviallyCopyable);
2964
2965 return StructSize && *StructSize == static_cast<int64_t>(getTypeSize(Ty));
2966 }
2967
2968 // FIXME: More cases to handle here (list by rsmith):
2969 // vectors (careful about, eg, vector of 3 foo)
2970 // _Complex int and friends
2971 // _Atomic T
2972 // Obj-C block pointers
2973 // Obj-C object pointers
2974 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
2975 // clk_event_t, queue_t, reserve_id_t)
2976 // There're also Obj-C class types and the Obj-C selector type, but I think it
2977 // makes sense for those to return false here.
2978
2979 return false;
2980}
2981
2983 unsigned count = 0;
2984 // Count ivars declared in class extension.
2985 for (const auto *Ext : OI->known_extensions())
2986 count += Ext->ivar_size();
2987
2988 // Count ivar defined in this class's implementation. This
2989 // includes synthesized ivars.
2990 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
2991 count += ImplDecl->ivar_size();
2992
2993 return count;
2994}
2995
2997 if (!E)
2998 return false;
2999
3000 // nullptr_t is always treated as null.
3001 if (E->getType()->isNullPtrType()) return true;
3002
3003 if (E->getType()->isAnyPointerType() &&
3006 return true;
3007
3008 // Unfortunately, __null has type 'int'.
3009 if (isa<GNUNullExpr>(E)) return true;
3010
3011 return false;
3012}
3013
3014/// Get the implementation of ObjCInterfaceDecl, or nullptr if none
3015/// exists.
3017 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
3018 I = ObjCImpls.find(D);
3019 if (I != ObjCImpls.end())
3020 return cast<ObjCImplementationDecl>(I->second);
3021 return nullptr;
3022}
3023
3024/// Get the implementation of ObjCCategoryDecl, or nullptr if none
3025/// exists.
3027 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
3028 I = ObjCImpls.find(D);
3029 if (I != ObjCImpls.end())
3030 return cast<ObjCCategoryImplDecl>(I->second);
3031 return nullptr;
3032}
3033
3034/// Set the implementation of ObjCInterfaceDecl.
3036 ObjCImplementationDecl *ImplD) {
3037 assert(IFaceD && ImplD && "Passed null params");
3038 ObjCImpls[IFaceD] = ImplD;
3039}
3040
3041/// Set the implementation of ObjCCategoryDecl.
3043 ObjCCategoryImplDecl *ImplD) {
3044 assert(CatD && ImplD && "Passed null params");
3045 ObjCImpls[CatD] = ImplD;
3046}
3047
3048const ObjCMethodDecl *
3050 return ObjCMethodRedecls.lookup(MD);
3051}
3052
3054 const ObjCMethodDecl *Redecl) {
3055 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
3056 ObjCMethodRedecls[MD] = Redecl;
3057}
3058
3060 const NamedDecl *ND) const {
3061 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
3062 return ID;
3063 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
3064 return CD->getClassInterface();
3065 if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
3066 return IMD->getClassInterface();
3067
3068 return nullptr;
3069}
3070
3071/// Get the copy initialization expression of VarDecl, or nullptr if
3072/// none exists.
3074 assert(VD && "Passed null params");
3075 assert(VD->hasAttr<BlocksAttr>() &&
3076 "getBlockVarCopyInits - not __block var");
3077 auto I = BlockVarCopyInits.find(VD);
3078 if (I != BlockVarCopyInits.end())
3079 return I->second;
3080 return {nullptr, false};
3081}
3082
3083/// Set the copy initialization expression of a block var decl.
3085 bool CanThrow) {
3086 assert(VD && CopyExpr && "Passed null params");
3087 assert(VD->hasAttr<BlocksAttr>() &&
3088 "setBlockVarCopyInits - not __block var");
3089 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
3090}
3091
3093 unsigned DataSize) const {
3094 if (!DataSize)
3096 else
3097 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
3098 "incorrect data size provided to CreateTypeSourceInfo!");
3099
3100 auto *TInfo =
3101 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
3102 new (TInfo) TypeSourceInfo(T, DataSize);
3103 return TInfo;
3104}
3105
3107 SourceLocation L) const {
3109 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
3110 return DI;
3111}
3112
3113const ASTRecordLayout &
3115 return getObjCLayout(D);
3116}
3117
3120 bool &AnyNonCanonArgs) {
3121 SmallVector<TemplateArgument, 16> CanonArgs(Args);
3122 AnyNonCanonArgs |= C.canonicalizeTemplateArguments(CanonArgs);
3123 return CanonArgs;
3124}
3125
3128 bool AnyNonCanonArgs = false;
3129 for (auto &Arg : Args) {
3130 TemplateArgument OrigArg = Arg;
3132 AnyNonCanonArgs |= !Arg.structurallyEquals(OrigArg);
3133 }
3134 return AnyNonCanonArgs;
3135}
3136
3137//===----------------------------------------------------------------------===//
3138// Type creation/memoization methods
3139//===----------------------------------------------------------------------===//
3140
3142ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
3143 unsigned fastQuals = quals.getFastQualifiers();
3144 quals.removeFastQualifiers();
3145
3146 // Check if we've already instantiated this type.
3147 llvm::FoldingSetNodeID ID;
3148 ExtQuals::Profile(ID, baseType, quals);
3149 void *insertPos = nullptr;
3150 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
3151 assert(eq->getQualifiers() == quals);
3152 return QualType(eq, fastQuals);
3153 }
3154
3155 // If the base type is not canonical, make the appropriate canonical type.
3156 QualType canon;
3157 if (!baseType->isCanonicalUnqualified()) {
3158 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
3159 canonSplit.Quals.addConsistentQualifiers(quals);
3160 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
3161
3162 // Re-find the insert position.
3163 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
3164 }
3165
3166 auto *eq = new (*this, alignof(ExtQuals)) ExtQuals(baseType, canon, quals);
3167 ExtQualNodes.InsertNode(eq, insertPos);
3168 return QualType(eq, fastQuals);
3169}
3170
3172 LangAS AddressSpace) const {
3173 QualType CanT = getCanonicalType(T);
3174 if (CanT.getAddressSpace() == AddressSpace)
3175 return T;
3176
3177 // If we are composing extended qualifiers together, merge together
3178 // into one ExtQuals node.
3179 QualifierCollector Quals;
3180 const Type *TypeNode = Quals.strip(T);
3181
3182 // If this type already has an address space specified, it cannot get
3183 // another one.
3184 assert(!Quals.hasAddressSpace() &&
3185 "Type cannot be in multiple addr spaces!");
3186 Quals.addAddressSpace(AddressSpace);
3187
3188 return getExtQualType(TypeNode, Quals);
3189}
3190
3192 // If the type is not qualified with an address space, just return it
3193 // immediately.
3194 if (!T.hasAddressSpace())
3195 return T;
3196
3197 QualifierCollector Quals;
3198 const Type *TypeNode;
3199 // For arrays, strip the qualifier off the element type, then reconstruct the
3200 // array type
3201 if (T.getTypePtr()->isArrayType()) {
3202 T = getUnqualifiedArrayType(T, Quals);
3203 TypeNode = T.getTypePtr();
3204 } else {
3205 // If we are composing extended qualifiers together, merge together
3206 // into one ExtQuals node.
3207 while (T.hasAddressSpace()) {
3208 TypeNode = Quals.strip(T);
3209
3210 // If the type no longer has an address space after stripping qualifiers,
3211 // jump out.
3212 if (!QualType(TypeNode, 0).hasAddressSpace())
3213 break;
3214
3215 // There might be sugar in the way. Strip it and try again.
3216 T = T.getSingleStepDesugaredType(*this);
3217 }
3218 }
3219
3220 Quals.removeAddressSpace();
3221
3222 // Removal of the address space can mean there are no longer any
3223 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
3224 // or required.
3225 if (Quals.hasNonFastQualifiers())
3226 return getExtQualType(TypeNode, Quals);
3227 else
3228 return QualType(TypeNode, Quals.getFastQualifiers());
3229}
3230
3231uint16_t
3233 assert(RD->isPolymorphic() &&
3234 "Attempted to get vtable pointer discriminator on a monomorphic type");
3235 std::unique_ptr<MangleContext> MC(createMangleContext());
3236 SmallString<256> Str;
3237 llvm::raw_svector_ostream Out(Str);
3238 MC->mangleCXXVTable(RD, Out);
3239 return llvm::getPointerAuthStableSipHash(Str);
3240}
3241
3242/// Encode a function type for use in the discriminator of a function pointer
3243/// type. We can't use the itanium scheme for this since C has quite permissive
3244/// rules for type compatibility that we need to be compatible with.
3245///
3246/// Formally, this function associates every function pointer type T with an
3247/// encoded string E(T). Let the equivalence relation T1 ~ T2 be defined as
3248/// E(T1) == E(T2). E(T) is part of the ABI of values of type T. C type
3249/// compatibility requires equivalent treatment under the ABI, so
3250/// CCompatible(T1, T2) must imply E(T1) == E(T2), that is, CCompatible must be
3251/// a subset of ~. Crucially, however, it must be a proper subset because
3252/// CCompatible is not an equivalence relation: for example, int[] is compatible
3253/// with both int[1] and int[2], but the latter are not compatible with each
3254/// other. Therefore this encoding function must be careful to only distinguish
3255/// types if there is no third type with which they are both required to be
3256/// compatible.
3258 raw_ostream &OS, QualType QT) {
3259 // FIXME: Consider address space qualifiers.
3260 const Type *T = QT.getCanonicalType().getTypePtr();
3261
3262 // FIXME: Consider using the C++ type mangling when we encounter a construct
3263 // that is incompatible with C.
3264
3265 switch (T->getTypeClass()) {
3266 case Type::Atomic:
3268 Ctx, OS, cast<AtomicType>(T)->getValueType());
3269
3270 case Type::LValueReference:
3271 OS << "R";
3274 return;
3275 case Type::RValueReference:
3276 OS << "O";
3279 return;
3280
3281 case Type::Pointer:
3282 // C11 6.7.6.1p2:
3283 // For two pointer types to be compatible, both shall be identically
3284 // qualified and both shall be pointers to compatible types.
3285 // FIXME: we should also consider pointee types.
3286 OS << "P";
3287 return;
3288
3289 case Type::ObjCObjectPointer:
3290 case Type::BlockPointer:
3291 OS << "P";
3292 return;
3293
3294 case Type::Complex:
3295 OS << "C";
3297 Ctx, OS, cast<ComplexType>(T)->getElementType());
3298
3299 case Type::VariableArray:
3300 case Type::ConstantArray:
3301 case Type::IncompleteArray:
3302 case Type::ArrayParameter:
3303 // C11 6.7.6.2p6:
3304 // For two array types to be compatible, both shall have compatible
3305 // element types, and if both size specifiers are present, and are integer
3306 // constant expressions, then both size specifiers shall have the same
3307 // constant value [...]
3308 //
3309 // So since ElemType[N] has to be compatible ElemType[], we can't encode the
3310 // width of the array.
3311 OS << "A";
3313 Ctx, OS, cast<ArrayType>(T)->getElementType());
3314
3315 case Type::ObjCInterface:
3316 case Type::ObjCObject:
3317 OS << "<objc_object>";
3318 return;
3319
3320 case Type::Enum: {
3321 // C11 6.7.2.2p4:
3322 // Each enumerated type shall be compatible with char, a signed integer
3323 // type, or an unsigned integer type.
3324 //
3325 // So we have to treat enum types as integers.
3326 QualType UnderlyingType = T->castAsEnumDecl()->getIntegerType();
3328 Ctx, OS, UnderlyingType.isNull() ? Ctx.IntTy : UnderlyingType);
3329 }
3330
3331 case Type::FunctionNoProto:
3332 case Type::FunctionProto: {
3333 // C11 6.7.6.3p15:
3334 // For two function types to be compatible, both shall specify compatible
3335 // return types. Moreover, the parameter type lists, if both are present,
3336 // shall agree in the number of parameters and in the use of the ellipsis
3337 // terminator; corresponding parameters shall have compatible types.
3338 //
3339 // That paragraph goes on to describe how unprototyped functions are to be
3340 // handled, which we ignore here. Unprototyped function pointers are hashed
3341 // as though they were prototyped nullary functions since thats probably
3342 // what the user meant. This behavior is non-conforming.
3343 // FIXME: If we add a "custom discriminator" function type attribute we
3344 // should encode functions as their discriminators.
3345 OS << "F";
3346 const auto *FuncType = cast<FunctionType>(T);
3347 encodeTypeForFunctionPointerAuth(Ctx, OS, FuncType->getReturnType());
3348 if (const auto *FPT = dyn_cast<FunctionProtoType>(FuncType)) {
3349 for (QualType Param : FPT->param_types()) {
3350 Param = Ctx.getSignatureParameterType(Param);
3351 encodeTypeForFunctionPointerAuth(Ctx, OS, Param);
3352 }
3353 if (FPT->isVariadic())
3354 OS << "z";
3355 }
3356 OS << "E";
3357 return;
3358 }
3359
3360 case Type::MemberPointer: {
3361 OS << "M";
3362 const auto *MPT = T->castAs<MemberPointerType>();
3364 Ctx, OS, QualType(MPT->getQualifier().getAsType(), 0));
3365 encodeTypeForFunctionPointerAuth(Ctx, OS, MPT->getPointeeType());
3366 return;
3367 }
3368 case Type::ExtVector:
3369 case Type::Vector:
3370 OS << "Dv" << Ctx.getTypeSizeInChars(T).getQuantity();
3371 break;
3372
3373 // Don't bother discriminating based on these types.
3374 case Type::Pipe:
3375 case Type::BitInt:
3376 case Type::ConstantMatrix:
3377 OS << "?";
3378 return;
3379
3380 case Type::Builtin: {
3381 const auto *BTy = T->castAs<BuiltinType>();
3382 switch (BTy->getKind()) {
3383#define SIGNED_TYPE(Id, SingletonId) \
3384 case BuiltinType::Id: \
3385 OS << "i"; \
3386 return;
3387#define UNSIGNED_TYPE(Id, SingletonId) \
3388 case BuiltinType::Id: \
3389 OS << "i"; \
3390 return;
3391#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
3392#define BUILTIN_TYPE(Id, SingletonId)
3393#include "clang/AST/BuiltinTypes.def"
3394 llvm_unreachable("placeholder types should not appear here.");
3395
3396 case BuiltinType::Half:
3397 OS << "Dh";
3398 return;
3399 case BuiltinType::Float:
3400 OS << "f";
3401 return;
3402 case BuiltinType::Double:
3403 OS << "d";
3404 return;
3405 case BuiltinType::LongDouble:
3406 OS << "e";
3407 return;
3408 case BuiltinType::Float16:
3409 OS << "DF16_";
3410 return;
3411 case BuiltinType::Float128:
3412 OS << "g";
3413 return;
3414
3415 case BuiltinType::Void:
3416 OS << "v";
3417 return;
3418
3419 case BuiltinType::ObjCId:
3420 case BuiltinType::ObjCClass:
3421 case BuiltinType::ObjCSel:
3422 case BuiltinType::NullPtr:
3423 OS << "P";
3424 return;
3425
3426 // Don't bother discriminating based on OpenCL types.
3427 case BuiltinType::OCLSampler:
3428 case BuiltinType::OCLEvent:
3429 case BuiltinType::OCLClkEvent:
3430 case BuiltinType::OCLQueue:
3431 case BuiltinType::OCLReserveID:
3432 case BuiltinType::BFloat16:
3433 case BuiltinType::VectorQuad:
3434 case BuiltinType::VectorPair:
3435 case BuiltinType::DMR1024:
3436 case BuiltinType::DMR2048:
3437 OS << "?";
3438 return;
3439
3440 // Don't bother discriminating based on these seldom-used types.
3441 case BuiltinType::Ibm128:
3442 return;
3443#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
3444 case BuiltinType::Id: \
3445 return;
3446#include "clang/Basic/OpenCLImageTypes.def"
3447#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
3448 case BuiltinType::Id: \
3449 return;
3450#include "clang/Basic/OpenCLExtensionTypes.def"
3451#define SVE_TYPE(Name, Id, SingletonId) \
3452 case BuiltinType::Id: \
3453 return;
3454#include "clang/Basic/AArch64ACLETypes.def"
3455#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
3456 case BuiltinType::Id: \
3457 return;
3458#include "clang/Basic/HLSLIntangibleTypes.def"
3459 case BuiltinType::Dependent:
3460 llvm_unreachable("should never get here");
3461#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
3462#include "clang/Basic/AMDGPUTypes.def"
3463 case BuiltinType::WasmExternRef:
3464#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
3465#include "clang/Basic/RISCVVTypes.def"
3466 llvm_unreachable("not yet implemented");
3467 }
3468 llvm_unreachable("should never get here");
3469 }
3470 case Type::Record: {
3471 const RecordDecl *RD = T->castAsCanonical<RecordType>()->getDecl();
3472 const IdentifierInfo *II = RD->getIdentifier();
3473
3474 // In C++, an immediate typedef of an anonymous struct or union
3475 // is considered to name it for ODR purposes, but C's specification
3476 // of type compatibility does not have a similar rule. Using the typedef
3477 // name in function type discriminators anyway, as we do here,
3478 // therefore technically violates the C standard: two function pointer
3479 // types defined in terms of two typedef'd anonymous structs with
3480 // different names are formally still compatible, but we are assigning
3481 // them different discriminators and therefore incompatible ABIs.
3482 //
3483 // This is a relatively minor violation that significantly improves
3484 // discrimination in some cases and has not caused problems in
3485 // practice. Regardless, it is now part of the ABI in places where
3486 // function type discrimination is used, and it can no longer be
3487 // changed except on new platforms.
3488
3489 if (!II)
3490 if (const TypedefNameDecl *Typedef = RD->getTypedefNameForAnonDecl())
3491 II = Typedef->getDeclName().getAsIdentifierInfo();
3492
3493 if (!II) {
3494 OS << "<anonymous_record>";
3495 return;
3496 }
3497 OS << II->getLength() << II->getName();
3498 return;
3499 }
3500 case Type::HLSLAttributedResource:
3501 case Type::HLSLInlineSpirv:
3502 llvm_unreachable("should never get here");
3503 break;
3504 case Type::DeducedTemplateSpecialization:
3505 case Type::Auto:
3506#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3507#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3508#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3509#define ABSTRACT_TYPE(Class, Base)
3510#define TYPE(Class, Base)
3511#include "clang/AST/TypeNodes.inc"
3512 llvm_unreachable("unexpected non-canonical or dependent type!");
3513 return;
3514 }
3515}
3516
3518 assert(!T->isDependentType() &&
3519 "cannot compute type discriminator of a dependent type");
3520
3521 SmallString<256> Str;
3522 llvm::raw_svector_ostream Out(Str);
3523
3524 if (T->isFunctionPointerType() || T->isFunctionReferenceType())
3525 T = T->getPointeeType();
3526
3527 if (T->isFunctionType()) {
3529 } else {
3530 T = T.getUnqualifiedType();
3531 // Calls to member function pointers don't need to worry about
3532 // language interop or the laxness of the C type compatibility rules.
3533 // We just mangle the member pointer type directly, which is
3534 // implicitly much stricter about type matching. However, we do
3535 // strip any top-level exception specification before this mangling.
3536 // C++23 requires calls to work when the function type is convertible
3537 // to the pointer type by a function pointer conversion, which can
3538 // change the exception specification. This does not technically
3539 // require the exception specification to not affect representation,
3540 // because the function pointer conversion is still always a direct
3541 // value conversion and therefore an opportunity to resign the
3542 // pointer. (This is in contrast to e.g. qualification conversions,
3543 // which can be applied in nested pointer positions, effectively
3544 // requiring qualified and unqualified representations to match.)
3545 // However, it is pragmatic to ignore exception specifications
3546 // because it allows a certain amount of `noexcept` mismatching
3547 // to not become a visible ODR problem. This also leaves some
3548 // room for the committee to add laxness to function pointer
3549 // conversions in future standards.
3550 if (auto *MPT = T->getAs<MemberPointerType>())
3551 if (MPT->isMemberFunctionPointer()) {
3552 QualType PointeeType = MPT->getPointeeType();
3553 if (PointeeType->castAs<FunctionProtoType>()->getExceptionSpecType() !=
3554 EST_None) {
3556 T = getMemberPointerType(FT, MPT->getQualifier(),
3557 MPT->getMostRecentCXXRecordDecl());
3558 }
3559 }
3560 std::unique_ptr<MangleContext> MC(createMangleContext());
3561 MC->mangleCanonicalTypeName(T, Out);
3562 }
3563
3564 return llvm::getPointerAuthStableSipHash(Str);
3565}
3566
3568 Qualifiers::GC GCAttr) const {
3569 QualType CanT = getCanonicalType(T);
3570 if (CanT.getObjCGCAttr() == GCAttr)
3571 return T;
3572
3573 if (const auto *ptr = T->getAs<PointerType>()) {
3574 QualType Pointee = ptr->getPointeeType();
3575 if (Pointee->isAnyPointerType()) {
3576 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
3577 return getPointerType(ResultType);
3578 }
3579 }
3580
3581 // If we are composing extended qualifiers together, merge together
3582 // into one ExtQuals node.
3583 QualifierCollector Quals;
3584 const Type *TypeNode = Quals.strip(T);
3585
3586 // If this type already has an ObjCGC specified, it cannot get
3587 // another one.
3588 assert(!Quals.hasObjCGCAttr() &&
3589 "Type cannot have multiple ObjCGCs!");
3590 Quals.addObjCGCAttr(GCAttr);
3591
3592 return getExtQualType(TypeNode, Quals);
3593}
3594
3596 if (const PointerType *Ptr = T->getAs<PointerType>()) {
3597 QualType Pointee = Ptr->getPointeeType();
3598 if (isPtrSizeAddressSpace(Pointee.getAddressSpace())) {
3599 return getPointerType(removeAddrSpaceQualType(Pointee));
3600 }
3601 }
3602 return T;
3603}
3604
3606 QualType WrappedTy, Expr *CountExpr, bool CountInBytes, bool OrNull,
3607 ArrayRef<TypeCoupledDeclRefInfo> DependentDecls) const {
3608 assert(WrappedTy->isPointerType() || WrappedTy->isArrayType());
3609
3610 llvm::FoldingSetNodeID ID;
3611 CountAttributedType::Profile(ID, WrappedTy, CountExpr, CountInBytes, OrNull);
3612
3613 void *InsertPos = nullptr;
3614 CountAttributedType *CATy =
3615 CountAttributedTypes.FindNodeOrInsertPos(ID, InsertPos);
3616 if (CATy)
3617 return QualType(CATy, 0);
3618
3619 QualType CanonTy = getCanonicalType(WrappedTy);
3620 size_t Size = CountAttributedType::totalSizeToAlloc<TypeCoupledDeclRefInfo>(
3621 DependentDecls.size());
3623 new (CATy) CountAttributedType(WrappedTy, CanonTy, CountExpr, CountInBytes,
3624 OrNull, DependentDecls);
3625 Types.push_back(CATy);
3626 CountAttributedTypes.InsertNode(CATy, InsertPos);
3627
3628 return QualType(CATy, 0);
3629}
3630
3633 llvm::function_ref<QualType(QualType)> Adjust) const {
3634 switch (Orig->getTypeClass()) {
3635 case Type::Attributed: {
3636 const auto *AT = cast<AttributedType>(Orig);
3637 return getAttributedType(AT->getAttrKind(),
3638 adjustType(AT->getModifiedType(), Adjust),
3639 adjustType(AT->getEquivalentType(), Adjust),
3640 AT->getAttr());
3641 }
3642
3643 case Type::BTFTagAttributed: {
3644 const auto *BTFT = dyn_cast<BTFTagAttributedType>(Orig);
3645 return getBTFTagAttributedType(BTFT->getAttr(),
3646 adjustType(BTFT->getWrappedType(), Adjust));
3647 }
3648
3649 case Type::Paren:
3650 return getParenType(
3651 adjustType(cast<ParenType>(Orig)->getInnerType(), Adjust));
3652
3653 case Type::Adjusted: {
3654 const auto *AT = cast<AdjustedType>(Orig);
3655 return getAdjustedType(AT->getOriginalType(),
3656 adjustType(AT->getAdjustedType(), Adjust));
3657 }
3658
3659 case Type::MacroQualified: {
3660 const auto *MQT = cast<MacroQualifiedType>(Orig);
3661 return getMacroQualifiedType(adjustType(MQT->getUnderlyingType(), Adjust),
3662 MQT->getMacroIdentifier());
3663 }
3664
3665 default:
3666 return Adjust(Orig);
3667 }
3668}
3669
3671 FunctionType::ExtInfo Info) {
3672 if (T->getExtInfo() == Info)
3673 return T;
3674
3676 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
3677 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
3678 } else {
3679 const auto *FPT = cast<FunctionProtoType>(T);
3680 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
3681 EPI.ExtInfo = Info;
3682 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
3683 }
3684
3685 return cast<FunctionType>(Result.getTypePtr());
3686}
3687
3689 QualType ResultType) {
3690 return adjustType(FunctionType, [&](QualType Orig) {
3691 if (const auto *FNPT = Orig->getAs<FunctionNoProtoType>())
3692 return getFunctionNoProtoType(ResultType, FNPT->getExtInfo());
3693
3694 const auto *FPT = Orig->castAs<FunctionProtoType>();
3695 return getFunctionType(ResultType, FPT->getParamTypes(),
3696 FPT->getExtProtoInfo());
3697 });
3698}
3699
3701 QualType ResultType) {
3702 FD = FD->getMostRecentDecl();
3703 while (true) {
3704 FD->setType(adjustFunctionResultType(FD->getType(), ResultType));
3705 if (FunctionDecl *Next = FD->getPreviousDecl())
3706 FD = Next;
3707 else
3708 break;
3709 }
3711 L->DeducedReturnType(FD, ResultType);
3712}
3713
3714/// Get a function type and produce the equivalent function type with the
3715/// specified exception specification. Type sugar that can be present on a
3716/// declaration of a function with an exception specification is permitted
3717/// and preserved. Other type sugar (for instance, typedefs) is not.
3719 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const {
3720 return adjustType(Orig, [&](QualType Ty) {
3721 const auto *Proto = Ty->castAs<FunctionProtoType>();
3722 return getFunctionType(Proto->getReturnType(), Proto->getParamTypes(),
3723 Proto->getExtProtoInfo().withExceptionSpec(ESI));
3724 });
3725}
3726
3734
3736 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3737 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3738 SmallVector<QualType, 16> Args(Proto->param_types().size());
3739 for (unsigned i = 0, n = Args.size(); i != n; ++i)
3740 Args[i] = removePtrSizeAddrSpace(Proto->param_types()[i]);
3741 return getFunctionType(RetTy, Args, Proto->getExtProtoInfo());
3742 }
3743
3744 if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) {
3745 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3746 return getFunctionNoProtoType(RetTy, Proto->getExtInfo());
3747 }
3748
3749 return T;
3750}
3751
3757
3759 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3760 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3761 EPI.ExtParameterInfos = nullptr;
3762 return getFunctionType(Proto->getReturnType(), Proto->param_types(), EPI);
3763 }
3764 return T;
3765}
3766
3772
3775 bool AsWritten) {
3776 // Update the type.
3777 QualType Updated =
3779 FD->setType(Updated);
3780
3781 if (!AsWritten)
3782 return;
3783
3784 // Update the type in the type source information too.
3785 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
3786 // If the type and the type-as-written differ, we may need to update
3787 // the type-as-written too.
3788 if (TSInfo->getType() != FD->getType())
3789 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
3790
3791 // FIXME: When we get proper type location information for exceptions,
3792 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
3793 // up the TypeSourceInfo;
3794 assert(TypeLoc::getFullDataSizeForType(Updated) ==
3795 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
3796 "TypeLoc size mismatch from updating exception specification");
3797 TSInfo->overrideType(Updated);
3798 }
3799}
3800
3801/// getComplexType - Return the uniqued reference to the type for a complex
3802/// number with the specified element type.
3804 // Unique pointers, to guarantee there is only one pointer of a particular
3805 // structure.
3806 llvm::FoldingSetNodeID ID;
3808
3809 void *InsertPos = nullptr;
3810 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
3811 return QualType(CT, 0);
3812
3813 // If the pointee type isn't canonical, this won't be a canonical type either,
3814 // so fill in the canonical type field.
3815 QualType Canonical;
3816 if (!T.isCanonical()) {
3817 Canonical = getComplexType(getCanonicalType(T));
3818
3819 // Get the new insert position for the node we care about.
3820 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
3821 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3822 }
3823 auto *New = new (*this, alignof(ComplexType)) ComplexType(T, Canonical);
3824 Types.push_back(New);
3825 ComplexTypes.InsertNode(New, InsertPos);
3826 return QualType(New, 0);
3827}
3828
3829/// getPointerType - Return the uniqued reference to the type for a pointer to
3830/// the specified type.
3832 // Unique pointers, to guarantee there is only one pointer of a particular
3833 // structure.
3834 llvm::FoldingSetNodeID ID;
3836
3837 void *InsertPos = nullptr;
3838 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3839 return QualType(PT, 0);
3840
3841 // If the pointee type isn't canonical, this won't be a canonical type either,
3842 // so fill in the canonical type field.
3843 QualType Canonical;
3844 if (!T.isCanonical()) {
3845 Canonical = getPointerType(getCanonicalType(T));
3846
3847 // Get the new insert position for the node we care about.
3848 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3849 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3850 }
3851 auto *New = new (*this, alignof(PointerType)) PointerType(T, Canonical);
3852 Types.push_back(New);
3853 PointerTypes.InsertNode(New, InsertPos);
3854 return QualType(New, 0);
3855}
3856
3858 llvm::FoldingSetNodeID ID;
3859 AdjustedType::Profile(ID, Orig, New);
3860 void *InsertPos = nullptr;
3861 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3862 if (AT)
3863 return QualType(AT, 0);
3864
3865 QualType Canonical = getCanonicalType(New);
3866
3867 // Get the new insert position for the node we care about.
3868 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3869 assert(!AT && "Shouldn't be in the map!");
3870
3871 AT = new (*this, alignof(AdjustedType))
3872 AdjustedType(Type::Adjusted, Orig, New, Canonical);
3873 Types.push_back(AT);
3874 AdjustedTypes.InsertNode(AT, InsertPos);
3875 return QualType(AT, 0);
3876}
3877
3879 llvm::FoldingSetNodeID ID;
3880 AdjustedType::Profile(ID, Orig, Decayed);
3881 void *InsertPos = nullptr;
3882 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3883 if (AT)
3884 return QualType(AT, 0);
3885
3886 QualType Canonical = getCanonicalType(Decayed);
3887
3888 // Get the new insert position for the node we care about.
3889 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3890 assert(!AT && "Shouldn't be in the map!");
3891
3892 AT = new (*this, alignof(DecayedType)) DecayedType(Orig, Decayed, Canonical);
3893 Types.push_back(AT);
3894 AdjustedTypes.InsertNode(AT, InsertPos);
3895 return QualType(AT, 0);
3896}
3897
3899 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
3900
3901 QualType Decayed;
3902
3903 // C99 6.7.5.3p7:
3904 // A declaration of a parameter as "array of type" shall be
3905 // adjusted to "qualified pointer to type", where the type
3906 // qualifiers (if any) are those specified within the [ and ] of
3907 // the array type derivation.
3908 if (T->isArrayType())
3909 Decayed = getArrayDecayedType(T);
3910
3911 // C99 6.7.5.3p8:
3912 // A declaration of a parameter as "function returning type"
3913 // shall be adjusted to "pointer to function returning type", as
3914 // in 6.3.2.1.
3915 if (T->isFunctionType())
3916 Decayed = getPointerType(T);
3917
3918 return getDecayedType(T, Decayed);
3919}
3920
3922 if (Ty->isArrayParameterType())
3923 return Ty;
3924 assert(Ty->isConstantArrayType() && "Ty must be an array type.");
3925 QualType DTy = Ty.getDesugaredType(*this);
3926 const auto *ATy = cast<ConstantArrayType>(DTy);
3927 llvm::FoldingSetNodeID ID;
3928 ATy->Profile(ID, *this, ATy->getElementType(), ATy->getZExtSize(),
3929 ATy->getSizeExpr(), ATy->getSizeModifier(),
3930 ATy->getIndexTypeQualifiers().getAsOpaqueValue());
3931 void *InsertPos = nullptr;
3932 ArrayParameterType *AT =
3933 ArrayParameterTypes.FindNodeOrInsertPos(ID, InsertPos);
3934 if (AT)
3935 return QualType(AT, 0);
3936
3937 QualType Canonical;
3938 if (!DTy.isCanonical()) {
3939 Canonical = getArrayParameterType(getCanonicalType(Ty));
3940
3941 // Get the new insert position for the node we care about.
3942 AT = ArrayParameterTypes.FindNodeOrInsertPos(ID, InsertPos);
3943 assert(!AT && "Shouldn't be in the map!");
3944 }
3945
3946 AT = new (*this, alignof(ArrayParameterType))
3947 ArrayParameterType(ATy, Canonical);
3948 Types.push_back(AT);
3949 ArrayParameterTypes.InsertNode(AT, InsertPos);
3950 return QualType(AT, 0);
3951}
3952
3953/// getBlockPointerType - Return the uniqued reference to the type for
3954/// a pointer to the specified block.
3956 assert(T->isFunctionType() && "block of function types only");
3957 // Unique pointers, to guarantee there is only one block of a particular
3958 // structure.
3959 llvm::FoldingSetNodeID ID;
3961
3962 void *InsertPos = nullptr;
3963 if (BlockPointerType *PT =
3964 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3965 return QualType(PT, 0);
3966
3967 // If the block pointee type isn't canonical, this won't be a canonical
3968 // type either so fill in the canonical type field.
3969 QualType Canonical;
3970 if (!T.isCanonical()) {
3972
3973 // Get the new insert position for the node we care about.
3974 BlockPointerType *NewIP =
3975 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3976 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3977 }
3978 auto *New =
3979 new (*this, alignof(BlockPointerType)) BlockPointerType(T, Canonical);
3980 Types.push_back(New);
3981 BlockPointerTypes.InsertNode(New, InsertPos);
3982 return QualType(New, 0);
3983}
3984
3985/// getLValueReferenceType - Return the uniqued reference to the type for an
3986/// lvalue reference to the specified type.
3988ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
3989 assert((!T->isPlaceholderType() ||
3990 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
3991 "Unresolved placeholder type");
3992
3993 // Unique pointers, to guarantee there is only one pointer of a particular
3994 // structure.
3995 llvm::FoldingSetNodeID ID;
3996 ReferenceType::Profile(ID, T, SpelledAsLValue);
3997
3998 void *InsertPos = nullptr;
3999 if (LValueReferenceType *RT =
4000 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
4001 return QualType(RT, 0);
4002
4003 const auto *InnerRef = T->getAs<ReferenceType>();
4004
4005 // If the referencee type isn't canonical, this won't be a canonical type
4006 // either, so fill in the canonical type field.
4007 QualType Canonical;
4008 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
4009 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
4010 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
4011
4012 // Get the new insert position for the node we care about.
4013 LValueReferenceType *NewIP =
4014 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
4015 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4016 }
4017
4018 auto *New = new (*this, alignof(LValueReferenceType))
4019 LValueReferenceType(T, Canonical, SpelledAsLValue);
4020 Types.push_back(New);
4021 LValueReferenceTypes.InsertNode(New, InsertPos);
4022
4023 return QualType(New, 0);
4024}
4025
4026/// getRValueReferenceType - Return the uniqued reference to the type for an
4027/// rvalue reference to the specified type.
4029 assert((!T->isPlaceholderType() ||
4030 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
4031 "Unresolved placeholder type");
4032
4033 // Unique pointers, to guarantee there is only one pointer of a particular
4034 // structure.
4035 llvm::FoldingSetNodeID ID;
4036 ReferenceType::Profile(ID, T, false);
4037
4038 void *InsertPos = nullptr;
4039 if (RValueReferenceType *RT =
4040 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
4041 return QualType(RT, 0);
4042
4043 const auto *InnerRef = T->getAs<ReferenceType>();
4044
4045 // If the referencee type isn't canonical, this won't be a canonical type
4046 // either, so fill in the canonical type field.
4047 QualType Canonical;
4048 if (InnerRef || !T.isCanonical()) {
4049 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
4050 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
4051
4052 // Get the new insert position for the node we care about.
4053 RValueReferenceType *NewIP =
4054 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
4055 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4056 }
4057
4058 auto *New = new (*this, alignof(RValueReferenceType))
4059 RValueReferenceType(T, Canonical);
4060 Types.push_back(New);
4061 RValueReferenceTypes.InsertNode(New, InsertPos);
4062 return QualType(New, 0);
4063}
4064
4066 NestedNameSpecifier Qualifier,
4067 const CXXRecordDecl *Cls) const {
4068 if (!Qualifier) {
4069 assert(Cls && "At least one of Qualifier or Cls must be provided");
4070 Qualifier = NestedNameSpecifier(getCanonicalTagType(Cls).getTypePtr());
4071 } else if (!Cls) {
4072 Cls = Qualifier.getAsRecordDecl();
4073 }
4074 // Unique pointers, to guarantee there is only one pointer of a particular
4075 // structure.
4076 llvm::FoldingSetNodeID ID;
4077 MemberPointerType::Profile(ID, T, Qualifier, Cls);
4078
4079 void *InsertPos = nullptr;
4080 if (MemberPointerType *PT =
4081 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4082 return QualType(PT, 0);
4083
4084 NestedNameSpecifier CanonicalQualifier = [&] {
4085 if (!Cls)
4086 return Qualifier.getCanonical();
4087 NestedNameSpecifier R(getCanonicalTagType(Cls).getTypePtr());
4088 assert(R.isCanonical());
4089 return R;
4090 }();
4091 // If the pointee or class type isn't canonical, this won't be a canonical
4092 // type either, so fill in the canonical type field.
4093 QualType Canonical;
4094 if (!T.isCanonical() || Qualifier != CanonicalQualifier) {
4095 Canonical =
4096 getMemberPointerType(getCanonicalType(T), CanonicalQualifier, Cls);
4097 assert(!cast<MemberPointerType>(Canonical)->isSugared());
4098 // Get the new insert position for the node we care about.
4099 [[maybe_unused]] MemberPointerType *NewIP =
4100 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4101 assert(!NewIP && "Shouldn't be in the map!");
4102 }
4103 auto *New = new (*this, alignof(MemberPointerType))
4104 MemberPointerType(T, Qualifier, Canonical);
4105 Types.push_back(New);
4106 MemberPointerTypes.InsertNode(New, InsertPos);
4107 return QualType(New, 0);
4108}
4109
4110/// getConstantArrayType - Return the unique reference to the type for an
4111/// array of the specified element type.
4113 const llvm::APInt &ArySizeIn,
4114 const Expr *SizeExpr,
4116 unsigned IndexTypeQuals) const {
4117 assert((EltTy->isDependentType() ||
4118 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
4119 "Constant array of VLAs is illegal!");
4120
4121 // We only need the size as part of the type if it's instantiation-dependent.
4122 if (SizeExpr && !SizeExpr->isInstantiationDependent())
4123 SizeExpr = nullptr;
4124
4125 // Convert the array size into a canonical width matching the pointer size for
4126 // the target.
4127 llvm::APInt ArySize(ArySizeIn);
4128 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
4129
4130 llvm::FoldingSetNodeID ID;
4131 ConstantArrayType::Profile(ID, *this, EltTy, ArySize.getZExtValue(), SizeExpr,
4132 ASM, IndexTypeQuals);
4133
4134 void *InsertPos = nullptr;
4135 if (ConstantArrayType *ATP =
4136 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
4137 return QualType(ATP, 0);
4138
4139 // If the element type isn't canonical or has qualifiers, or the array bound
4140 // is instantiation-dependent, this won't be a canonical type either, so fill
4141 // in the canonical type field.
4142 QualType Canon;
4143 // FIXME: Check below should look for qualifiers behind sugar.
4144 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) {
4145 SplitQualType canonSplit = getCanonicalType(EltTy).split();
4146 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr,
4147 ASM, IndexTypeQuals);
4148 Canon = getQualifiedType(Canon, canonSplit.Quals);
4149
4150 // Get the new insert position for the node we care about.
4151 ConstantArrayType *NewIP =
4152 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
4153 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4154 }
4155
4156 auto *New = ConstantArrayType::Create(*this, EltTy, Canon, ArySize, SizeExpr,
4157 ASM, IndexTypeQuals);
4158 ConstantArrayTypes.InsertNode(New, InsertPos);
4159 Types.push_back(New);
4160 return QualType(New, 0);
4161}
4162
4163/// getVariableArrayDecayedType - Turns the given type, which may be
4164/// variably-modified, into the corresponding type with all the known
4165/// sizes replaced with [*].
4167 // Vastly most common case.
4168 if (!type->isVariablyModifiedType()) return type;
4169
4170 QualType result;
4171
4172 SplitQualType split = type.getSplitDesugaredType();
4173 const Type *ty = split.Ty;
4174 switch (ty->getTypeClass()) {
4175#define TYPE(Class, Base)
4176#define ABSTRACT_TYPE(Class, Base)
4177#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4178#include "clang/AST/TypeNodes.inc"
4179 llvm_unreachable("didn't desugar past all non-canonical types?");
4180
4181 // These types should never be variably-modified.
4182 case Type::Builtin:
4183 case Type::Complex:
4184 case Type::Vector:
4185 case Type::DependentVector:
4186 case Type::ExtVector:
4187 case Type::DependentSizedExtVector:
4188 case Type::ConstantMatrix:
4189 case Type::DependentSizedMatrix:
4190 case Type::DependentAddressSpace:
4191 case Type::ObjCObject:
4192 case Type::ObjCInterface:
4193 case Type::ObjCObjectPointer:
4194 case Type::Record:
4195 case Type::Enum:
4196 case Type::UnresolvedUsing:
4197 case Type::TypeOfExpr:
4198 case Type::TypeOf:
4199 case Type::Decltype:
4200 case Type::UnaryTransform:
4201 case Type::DependentName:
4202 case Type::InjectedClassName:
4203 case Type::TemplateSpecialization:
4204 case Type::TemplateTypeParm:
4205 case Type::SubstTemplateTypeParmPack:
4206 case Type::SubstBuiltinTemplatePack:
4207 case Type::Auto:
4208 case Type::DeducedTemplateSpecialization:
4209 case Type::PackExpansion:
4210 case Type::PackIndexing:
4211 case Type::BitInt:
4212 case Type::DependentBitInt:
4213 case Type::ArrayParameter:
4214 case Type::HLSLAttributedResource:
4215 case Type::HLSLInlineSpirv:
4216 llvm_unreachable("type should never be variably-modified");
4217
4218 // These types can be variably-modified but should never need to
4219 // further decay.
4220 case Type::FunctionNoProto:
4221 case Type::FunctionProto:
4222 case Type::BlockPointer:
4223 case Type::MemberPointer:
4224 case Type::Pipe:
4225 return type;
4226
4227 // These types can be variably-modified. All these modifications
4228 // preserve structure except as noted by comments.
4229 // TODO: if we ever care about optimizing VLAs, there are no-op
4230 // optimizations available here.
4231 case Type::Pointer:
4234 break;
4235
4236 case Type::LValueReference: {
4237 const auto *lv = cast<LValueReferenceType>(ty);
4238 result = getLValueReferenceType(
4239 getVariableArrayDecayedType(lv->getPointeeType()),
4240 lv->isSpelledAsLValue());
4241 break;
4242 }
4243
4244 case Type::RValueReference: {
4245 const auto *lv = cast<RValueReferenceType>(ty);
4246 result = getRValueReferenceType(
4247 getVariableArrayDecayedType(lv->getPointeeType()));
4248 break;
4249 }
4250
4251 case Type::Atomic: {
4252 const auto *at = cast<AtomicType>(ty);
4253 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
4254 break;
4255 }
4256
4257 case Type::ConstantArray: {
4258 const auto *cat = cast<ConstantArrayType>(ty);
4259 result = getConstantArrayType(
4260 getVariableArrayDecayedType(cat->getElementType()),
4261 cat->getSize(),
4262 cat->getSizeExpr(),
4263 cat->getSizeModifier(),
4264 cat->getIndexTypeCVRQualifiers());
4265 break;
4266 }
4267
4268 case Type::DependentSizedArray: {
4269 const auto *dat = cast<DependentSizedArrayType>(ty);
4271 getVariableArrayDecayedType(dat->getElementType()), dat->getSizeExpr(),
4272 dat->getSizeModifier(), dat->getIndexTypeCVRQualifiers());
4273 break;
4274 }
4275
4276 // Turn incomplete types into [*] types.
4277 case Type::IncompleteArray: {
4278 const auto *iat = cast<IncompleteArrayType>(ty);
4279 result =
4281 /*size*/ nullptr, ArraySizeModifier::Normal,
4282 iat->getIndexTypeCVRQualifiers());
4283 break;
4284 }
4285
4286 // Turn VLA types into [*] types.
4287 case Type::VariableArray: {
4288 const auto *vat = cast<VariableArrayType>(ty);
4289 result =
4291 /*size*/ nullptr, ArraySizeModifier::Star,
4292 vat->getIndexTypeCVRQualifiers());
4293 break;
4294 }
4295 }
4296
4297 // Apply the top-level qualifiers from the original.
4298 return getQualifiedType(result, split.Quals);
4299}
4300
4301/// getVariableArrayType - Returns a non-unique reference to the type for a
4302/// variable array of the specified element type.
4305 unsigned IndexTypeQuals) const {
4306 // Since we don't unique expressions, it isn't possible to unique VLA's
4307 // that have an expression provided for their size.
4308 QualType Canon;
4309
4310 // Be sure to pull qualifiers off the element type.
4311 // FIXME: Check below should look for qualifiers behind sugar.
4312 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
4313 SplitQualType canonSplit = getCanonicalType(EltTy).split();
4314 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
4315 IndexTypeQuals);
4316 Canon = getQualifiedType(Canon, canonSplit.Quals);
4317 }
4318
4319 auto *New = new (*this, alignof(VariableArrayType))
4320 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals);
4321
4322 VariableArrayTypes.push_back(New);
4323 Types.push_back(New);
4324 return QualType(New, 0);
4325}
4326
4327/// getDependentSizedArrayType - Returns a non-unique reference to
4328/// the type for a dependently-sized array of the specified element
4329/// type.
4333 unsigned elementTypeQuals) const {
4334 assert((!numElements || numElements->isTypeDependent() ||
4335 numElements->isValueDependent()) &&
4336 "Size must be type- or value-dependent!");
4337
4338 SplitQualType canonElementType = getCanonicalType(elementType).split();
4339
4340 void *insertPos = nullptr;
4341 llvm::FoldingSetNodeID ID;
4343 ID, *this, numElements ? QualType(canonElementType.Ty, 0) : elementType,
4344 ASM, elementTypeQuals, numElements);
4345
4346 // Look for an existing type with these properties.
4347 DependentSizedArrayType *canonTy =
4348 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
4349
4350 // Dependently-sized array types that do not have a specified number
4351 // of elements will have their sizes deduced from a dependent
4352 // initializer.
4353 if (!numElements) {
4354 if (canonTy)
4355 return QualType(canonTy, 0);
4356
4357 auto *newType = new (*this, alignof(DependentSizedArrayType))
4358 DependentSizedArrayType(elementType, QualType(), numElements, ASM,
4359 elementTypeQuals);
4360 DependentSizedArrayTypes.InsertNode(newType, insertPos);
4361 Types.push_back(newType);
4362 return QualType(newType, 0);
4363 }
4364
4365 // If we don't have one, build one.
4366 if (!canonTy) {
4367 canonTy = new (*this, alignof(DependentSizedArrayType))
4368 DependentSizedArrayType(QualType(canonElementType.Ty, 0), QualType(),
4369 numElements, ASM, elementTypeQuals);
4370 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
4371 Types.push_back(canonTy);
4372 }
4373
4374 // Apply qualifiers from the element type to the array.
4375 QualType canon = getQualifiedType(QualType(canonTy,0),
4376 canonElementType.Quals);
4377
4378 // If we didn't need extra canonicalization for the element type or the size
4379 // expression, then just use that as our result.
4380 if (QualType(canonElementType.Ty, 0) == elementType &&
4381 canonTy->getSizeExpr() == numElements)
4382 return canon;
4383
4384 // Otherwise, we need to build a type which follows the spelling
4385 // of the element type.
4386 auto *sugaredType = new (*this, alignof(DependentSizedArrayType))
4387 DependentSizedArrayType(elementType, canon, numElements, ASM,
4388 elementTypeQuals);
4389 Types.push_back(sugaredType);
4390 return QualType(sugaredType, 0);
4391}
4392
4395 unsigned elementTypeQuals) const {
4396 llvm::FoldingSetNodeID ID;
4397 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
4398
4399 void *insertPos = nullptr;
4400 if (IncompleteArrayType *iat =
4401 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
4402 return QualType(iat, 0);
4403
4404 // If the element type isn't canonical, this won't be a canonical type
4405 // either, so fill in the canonical type field. We also have to pull
4406 // qualifiers off the element type.
4407 QualType canon;
4408
4409 // FIXME: Check below should look for qualifiers behind sugar.
4410 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
4411 SplitQualType canonSplit = getCanonicalType(elementType).split();
4412 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
4413 ASM, elementTypeQuals);
4414 canon = getQualifiedType(canon, canonSplit.Quals);
4415
4416 // Get the new insert position for the node we care about.
4417 IncompleteArrayType *existing =
4418 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
4419 assert(!existing && "Shouldn't be in the map!"); (void) existing;
4420 }
4421
4422 auto *newType = new (*this, alignof(IncompleteArrayType))
4423 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
4424
4425 IncompleteArrayTypes.InsertNode(newType, insertPos);
4426 Types.push_back(newType);
4427 return QualType(newType, 0);
4428}
4429
4432#define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS) \
4433 {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount::getScalable(ELTS), \
4434 NUMVECTORS};
4435
4436#define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS) \
4437 {ELTTY, llvm::ElementCount::getScalable(ELTS), NUMVECTORS};
4438
4439 switch (Ty->getKind()) {
4440 default:
4441 llvm_unreachable("Unsupported builtin vector type");
4442
4443#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4444 ElBits, NF, IsSigned) \
4445 case BuiltinType::Id: \
4446 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4447 llvm::ElementCount::getScalable(NumEls), NF};
4448#define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4449 ElBits, NF) \
4450 case BuiltinType::Id: \
4451 return {ElBits == 16 ? HalfTy : (ElBits == 32 ? FloatTy : DoubleTy), \
4452 llvm::ElementCount::getScalable(NumEls), NF};
4453#define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4454 ElBits, NF) \
4455 case BuiltinType::Id: \
4456 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4457#define SVE_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4458 ElBits, NF) \
4459 case BuiltinType::Id: \
4460 return {MFloat8Ty, llvm::ElementCount::getScalable(NumEls), NF};
4461#define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4462 case BuiltinType::Id: \
4463 return {BoolTy, llvm::ElementCount::getScalable(NumEls), NF};
4464#include "clang/Basic/AArch64ACLETypes.def"
4465
4466#define RVV_VECTOR_TYPE_INT(Name, Id, SingletonId, NumEls, ElBits, NF, \
4467 IsSigned) \
4468 case BuiltinType::Id: \
4469 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4470 llvm::ElementCount::getScalable(NumEls), NF};
4471#define RVV_VECTOR_TYPE_FLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4472 case BuiltinType::Id: \
4473 return {ElBits == 16 ? Float16Ty : (ElBits == 32 ? FloatTy : DoubleTy), \
4474 llvm::ElementCount::getScalable(NumEls), NF};
4475#define RVV_VECTOR_TYPE_BFLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4476 case BuiltinType::Id: \
4477 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4478#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4479 case BuiltinType::Id: \
4480 return {BoolTy, llvm::ElementCount::getScalable(NumEls), 1};
4481#include "clang/Basic/RISCVVTypes.def"
4482 }
4483}
4484
4485/// getExternrefType - Return a WebAssembly externref type, which represents an
4486/// opaque reference to a host value.
4488 if (Target->getTriple().isWasm() && Target->hasFeature("reference-types")) {
4489#define WASM_REF_TYPE(Name, MangledName, Id, SingletonId, AS) \
4490 if (BuiltinType::Id == BuiltinType::WasmExternRef) \
4491 return SingletonId;
4492#include "clang/Basic/WebAssemblyReferenceTypes.def"
4493 }
4494 llvm_unreachable(
4495 "shouldn't try to generate type externref outside WebAssembly target");
4496}
4497
4498/// getScalableVectorType - Return the unique reference to a scalable vector
4499/// type of the specified element type and size. VectorType must be a built-in
4500/// type.
4502 unsigned NumFields) const {
4503 auto K = llvm::ScalableVecTyKey{EltTy, NumElts, NumFields};
4504 if (auto It = ScalableVecTyMap.find(K); It != ScalableVecTyMap.end())
4505 return It->second;
4506
4507 if (Target->hasAArch64ACLETypes()) {
4508 uint64_t EltTySize = getTypeSize(EltTy);
4509
4510#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4511 ElBits, NF, IsSigned) \
4512 if (EltTy->hasIntegerRepresentation() && !EltTy->isBooleanType() && \
4513 EltTy->hasSignedIntegerRepresentation() == IsSigned && \
4514 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4515 return ScalableVecTyMap[K] = SingletonId; \
4516 }
4517#define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4518 ElBits, NF) \
4519 if (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4520 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4521 return ScalableVecTyMap[K] = SingletonId; \
4522 }
4523#define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4524 ElBits, NF) \
4525 if (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4526 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4527 return ScalableVecTyMap[K] = SingletonId; \
4528 }
4529#define SVE_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4530 ElBits, NF) \
4531 if (EltTy->isMFloat8Type() && EltTySize == ElBits && \
4532 NumElts == (NumEls * NF) && NumFields == 1) { \
4533 return ScalableVecTyMap[K] = SingletonId; \
4534 }
4535#define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4536 if (EltTy->isBooleanType() && NumElts == (NumEls * NF) && NumFields == 1) \
4537 return ScalableVecTyMap[K] = SingletonId;
4538#include "clang/Basic/AArch64ACLETypes.def"
4539 } else if (Target->hasRISCVVTypes()) {
4540 uint64_t EltTySize = getTypeSize(EltTy);
4541#define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned, \
4542 IsFP, IsBF) \
4543 if (!EltTy->isBooleanType() && \
4544 ((EltTy->hasIntegerRepresentation() && \
4545 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \
4546 (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4547 IsFP && !IsBF) || \
4548 (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4549 IsBF && !IsFP)) && \
4550 EltTySize == ElBits && NumElts == NumEls && NumFields == NF) \
4551 return ScalableVecTyMap[K] = SingletonId;
4552#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4553 if (EltTy->isBooleanType() && NumElts == NumEls) \
4554 return ScalableVecTyMap[K] = SingletonId;
4555#include "clang/Basic/RISCVVTypes.def"
4556 }
4557 return QualType();
4558}
4559
4560/// getVectorType - Return the unique reference to a vector type of
4561/// the specified element type and size. VectorType must be a built-in type.
4563 VectorKind VecKind) const {
4564 assert(vecType->isBuiltinType() ||
4565 (vecType->isBitIntType() &&
4566 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4567 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits())));
4568
4569 // Check if we've already instantiated a vector of this type.
4570 llvm::FoldingSetNodeID ID;
4571 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
4572
4573 void *InsertPos = nullptr;
4574 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4575 return QualType(VTP, 0);
4576
4577 // If the element type isn't canonical, this won't be a canonical type either,
4578 // so fill in the canonical type field.
4579 QualType Canonical;
4580 if (!vecType.isCanonical()) {
4581 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
4582
4583 // Get the new insert position for the node we care about.
4584 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4585 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4586 }
4587 auto *New = new (*this, alignof(VectorType))
4588 VectorType(vecType, NumElts, Canonical, VecKind);
4589 VectorTypes.InsertNode(New, InsertPos);
4590 Types.push_back(New);
4591 return QualType(New, 0);
4592}
4593
4595 SourceLocation AttrLoc,
4596 VectorKind VecKind) const {
4597 llvm::FoldingSetNodeID ID;
4598 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
4599 VecKind);
4600 void *InsertPos = nullptr;
4601 DependentVectorType *Canon =
4602 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4604
4605 if (Canon) {
4606 New = new (*this, alignof(DependentVectorType)) DependentVectorType(
4607 VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
4608 } else {
4609 QualType CanonVecTy = getCanonicalType(VecType);
4610 if (CanonVecTy == VecType) {
4611 New = new (*this, alignof(DependentVectorType))
4612 DependentVectorType(VecType, QualType(), SizeExpr, AttrLoc, VecKind);
4613
4614 DependentVectorType *CanonCheck =
4615 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4616 assert(!CanonCheck &&
4617 "Dependent-sized vector_size canonical type broken");
4618 (void)CanonCheck;
4619 DependentVectorTypes.InsertNode(New, InsertPos);
4620 } else {
4621 QualType CanonTy = getDependentVectorType(CanonVecTy, SizeExpr,
4622 SourceLocation(), VecKind);
4623 New = new (*this, alignof(DependentVectorType))
4624 DependentVectorType(VecType, CanonTy, SizeExpr, AttrLoc, VecKind);
4625 }
4626 }
4627
4628 Types.push_back(New);
4629 return QualType(New, 0);
4630}
4631
4632/// getExtVectorType - Return the unique reference to an extended vector type of
4633/// the specified element type and size. VectorType must be a built-in type.
4635 unsigned NumElts) const {
4636 assert(vecType->isBuiltinType() || vecType->isDependentType() ||
4637 (vecType->isBitIntType() &&
4638 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4639 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits())));
4640
4641 // Check if we've already instantiated a vector of this type.
4642 llvm::FoldingSetNodeID ID;
4643 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
4645 void *InsertPos = nullptr;
4646 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4647 return QualType(VTP, 0);
4648
4649 // If the element type isn't canonical, this won't be a canonical type either,
4650 // so fill in the canonical type field.
4651 QualType Canonical;
4652 if (!vecType.isCanonical()) {
4653 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
4654
4655 // Get the new insert position for the node we care about.
4656 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4657 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4658 }
4659 auto *New = new (*this, alignof(ExtVectorType))
4660 ExtVectorType(vecType, NumElts, Canonical);
4661 VectorTypes.InsertNode(New, InsertPos);
4662 Types.push_back(New);
4663 return QualType(New, 0);
4664}
4665
4668 Expr *SizeExpr,
4669 SourceLocation AttrLoc) const {
4670 llvm::FoldingSetNodeID ID;
4672 SizeExpr);
4673
4674 void *InsertPos = nullptr;
4676 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4678 if (Canon) {
4679 // We already have a canonical version of this array type; use it as
4680 // the canonical type for a newly-built type.
4681 New = new (*this, alignof(DependentSizedExtVectorType))
4682 DependentSizedExtVectorType(vecType, QualType(Canon, 0), SizeExpr,
4683 AttrLoc);
4684 } else {
4685 QualType CanonVecTy = getCanonicalType(vecType);
4686 if (CanonVecTy == vecType) {
4687 New = new (*this, alignof(DependentSizedExtVectorType))
4688 DependentSizedExtVectorType(vecType, QualType(), SizeExpr, AttrLoc);
4689
4690 DependentSizedExtVectorType *CanonCheck
4691 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4692 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
4693 (void)CanonCheck;
4694 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
4695 } else {
4696 QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
4697 SourceLocation());
4698 New = new (*this, alignof(DependentSizedExtVectorType))
4699 DependentSizedExtVectorType(vecType, CanonExtTy, SizeExpr, AttrLoc);
4700 }
4701 }
4702
4703 Types.push_back(New);
4704 return QualType(New, 0);
4705}
4706
4708 unsigned NumColumns) const {
4709 llvm::FoldingSetNodeID ID;
4710 ConstantMatrixType::Profile(ID, ElementTy, NumRows, NumColumns,
4711 Type::ConstantMatrix);
4712
4713 assert(MatrixType::isValidElementType(ElementTy) &&
4714 "need a valid element type");
4715 assert(NumRows > 0 && NumRows <= LangOpts.MaxMatrixDimension &&
4716 NumColumns > 0 && NumColumns <= LangOpts.MaxMatrixDimension &&
4717 "need valid matrix dimensions");
4718 void *InsertPos = nullptr;
4719 if (ConstantMatrixType *MTP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos))
4720 return QualType(MTP, 0);
4721
4722 QualType Canonical;
4723 if (!ElementTy.isCanonical()) {
4724 Canonical =
4725 getConstantMatrixType(getCanonicalType(ElementTy), NumRows, NumColumns);
4726
4727 ConstantMatrixType *NewIP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4728 assert(!NewIP && "Matrix type shouldn't already exist in the map");
4729 (void)NewIP;
4730 }
4731
4732 auto *New = new (*this, alignof(ConstantMatrixType))
4733 ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical);
4734 MatrixTypes.InsertNode(New, InsertPos);
4735 Types.push_back(New);
4736 return QualType(New, 0);
4737}
4738
4740 Expr *RowExpr,
4741 Expr *ColumnExpr,
4742 SourceLocation AttrLoc) const {
4743 QualType CanonElementTy = getCanonicalType(ElementTy);
4744 llvm::FoldingSetNodeID ID;
4745 DependentSizedMatrixType::Profile(ID, *this, CanonElementTy, RowExpr,
4746 ColumnExpr);
4747
4748 void *InsertPos = nullptr;
4750 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4751
4752 if (!Canon) {
4753 Canon = new (*this, alignof(DependentSizedMatrixType))
4754 DependentSizedMatrixType(CanonElementTy, QualType(), RowExpr,
4755 ColumnExpr, AttrLoc);
4756#ifndef NDEBUG
4757 DependentSizedMatrixType *CanonCheck =
4758 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4759 assert(!CanonCheck && "Dependent-sized matrix canonical type broken");
4760#endif
4761 DependentSizedMatrixTypes.InsertNode(Canon, InsertPos);
4762 Types.push_back(Canon);
4763 }
4764
4765 // Already have a canonical version of the matrix type
4766 //
4767 // If it exactly matches the requested type, use it directly.
4768 if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr &&
4769 Canon->getRowExpr() == ColumnExpr)
4770 return QualType(Canon, 0);
4771
4772 // Use Canon as the canonical type for newly-built type.
4774 DependentSizedMatrixType(ElementTy, QualType(Canon, 0), RowExpr,
4775 ColumnExpr, AttrLoc);
4776 Types.push_back(New);
4777 return QualType(New, 0);
4778}
4779
4781 Expr *AddrSpaceExpr,
4782 SourceLocation AttrLoc) const {
4783 assert(AddrSpaceExpr->isInstantiationDependent());
4784
4785 QualType canonPointeeType = getCanonicalType(PointeeType);
4786
4787 void *insertPos = nullptr;
4788 llvm::FoldingSetNodeID ID;
4789 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
4790 AddrSpaceExpr);
4791
4792 DependentAddressSpaceType *canonTy =
4793 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
4794
4795 if (!canonTy) {
4796 canonTy = new (*this, alignof(DependentAddressSpaceType))
4797 DependentAddressSpaceType(canonPointeeType, QualType(), AddrSpaceExpr,
4798 AttrLoc);
4799 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
4800 Types.push_back(canonTy);
4801 }
4802
4803 if (canonPointeeType == PointeeType &&
4804 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
4805 return QualType(canonTy, 0);
4806
4807 auto *sugaredType = new (*this, alignof(DependentAddressSpaceType))
4808 DependentAddressSpaceType(PointeeType, QualType(canonTy, 0),
4809 AddrSpaceExpr, AttrLoc);
4810 Types.push_back(sugaredType);
4811 return QualType(sugaredType, 0);
4812}
4813
4814/// Determine whether \p T is canonical as the result type of a function.
4816 return T.isCanonical() &&
4817 (T.getObjCLifetime() == Qualifiers::OCL_None ||
4818 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
4819}
4820
4821/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
4822QualType
4824 const FunctionType::ExtInfo &Info) const {
4825 // FIXME: This assertion cannot be enabled (yet) because the ObjC rewriter
4826 // functionality creates a function without a prototype regardless of
4827 // language mode (so it makes them even in C++). Once the rewriter has been
4828 // fixed, this assertion can be enabled again.
4829 //assert(!LangOpts.requiresStrictPrototypes() &&
4830 // "strict prototypes are disabled");
4831
4832 // Unique functions, to guarantee there is only one function of a particular
4833 // structure.
4834 llvm::FoldingSetNodeID ID;
4835 FunctionNoProtoType::Profile(ID, ResultTy, Info);
4836
4837 void *InsertPos = nullptr;
4838 if (FunctionNoProtoType *FT =
4839 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
4840 return QualType(FT, 0);
4841
4842 QualType Canonical;
4843 if (!isCanonicalResultType(ResultTy)) {
4844 Canonical =
4846
4847 // Get the new insert position for the node we care about.
4848 FunctionNoProtoType *NewIP =
4849 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
4850 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4851 }
4852
4853 auto *New = new (*this, alignof(FunctionNoProtoType))
4854 FunctionNoProtoType(ResultTy, Canonical, Info);
4855 Types.push_back(New);
4856 FunctionNoProtoTypes.InsertNode(New, InsertPos);
4857 return QualType(New, 0);
4858}
4859
4862 CanQualType CanResultType = getCanonicalType(ResultType);
4863
4864 // Canonical result types do not have ARC lifetime qualifiers.
4865 if (CanResultType.getQualifiers().hasObjCLifetime()) {
4866 Qualifiers Qs = CanResultType.getQualifiers();
4867 Qs.removeObjCLifetime();
4869 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
4870 }
4871
4872 return CanResultType;
4873}
4874
4876 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
4877 if (ESI.Type == EST_None)
4878 return true;
4879 if (!NoexceptInType)
4880 return false;
4881
4882 // C++17 onwards: exception specification is part of the type, as a simple
4883 // boolean "can this function type throw".
4884 if (ESI.Type == EST_BasicNoexcept)
4885 return true;
4886
4887 // A noexcept(expr) specification is (possibly) canonical if expr is
4888 // value-dependent.
4889 if (ESI.Type == EST_DependentNoexcept)
4890 return true;
4891
4892 // A dynamic exception specification is canonical if it only contains pack
4893 // expansions (so we can't tell whether it's non-throwing) and all its
4894 // contained types are canonical.
4895 if (ESI.Type == EST_Dynamic) {
4896 bool AnyPackExpansions = false;
4897 for (QualType ET : ESI.Exceptions) {
4898 if (!ET.isCanonical())
4899 return false;
4900 if (ET->getAs<PackExpansionType>())
4901 AnyPackExpansions = true;
4902 }
4903 return AnyPackExpansions;
4904 }
4905
4906 return false;
4907}
4908
4909QualType ASTContext::getFunctionTypeInternal(
4910 QualType ResultTy, ArrayRef<QualType> ArgArray,
4911 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
4912 size_t NumArgs = ArgArray.size();
4913
4914 // Unique functions, to guarantee there is only one function of a particular
4915 // structure.
4916 llvm::FoldingSetNodeID ID;
4917 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
4918 *this, true);
4919
4920 QualType Canonical;
4921 bool Unique = false;
4922
4923 void *InsertPos = nullptr;
4924 if (FunctionProtoType *FPT =
4925 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
4926 QualType Existing = QualType(FPT, 0);
4927
4928 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
4929 // it so long as our exception specification doesn't contain a dependent
4930 // noexcept expression, or we're just looking for a canonical type.
4931 // Otherwise, we're going to need to create a type
4932 // sugar node to hold the concrete expression.
4933 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
4934 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
4935 return Existing;
4936
4937 // We need a new type sugar node for this one, to hold the new noexcept
4938 // expression. We do no canonicalization here, but that's OK since we don't
4939 // expect to see the same noexcept expression much more than once.
4940 Canonical = getCanonicalType(Existing);
4941 Unique = true;
4942 }
4943
4944 bool NoexceptInType = getLangOpts().CPlusPlus17;
4945 bool IsCanonicalExceptionSpec =
4947
4948 // Determine whether the type being created is already canonical or not.
4949 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
4950 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
4951 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
4952 if (!ArgArray[i].isCanonicalAsParam())
4953 isCanonical = false;
4954
4955 if (OnlyWantCanonical)
4956 assert(isCanonical &&
4957 "given non-canonical parameters constructing canonical type");
4958
4959 // If this type isn't canonical, get the canonical version of it if we don't
4960 // already have it. The exception spec is only partially part of the
4961 // canonical type, and only in C++17 onwards.
4962 if (!isCanonical && Canonical.isNull()) {
4963 SmallVector<QualType, 16> CanonicalArgs;
4964 CanonicalArgs.reserve(NumArgs);
4965 for (unsigned i = 0; i != NumArgs; ++i)
4966 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
4967
4968 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
4969 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
4970 CanonicalEPI.HasTrailingReturn = false;
4971
4972 if (IsCanonicalExceptionSpec) {
4973 // Exception spec is already OK.
4974 } else if (NoexceptInType) {
4975 switch (EPI.ExceptionSpec.Type) {
4977 // We don't know yet. It shouldn't matter what we pick here; no-one
4978 // should ever look at this.
4979 [[fallthrough]];
4980 case EST_None: case EST_MSAny: case EST_NoexceptFalse:
4981 CanonicalEPI.ExceptionSpec.Type = EST_None;
4982 break;
4983
4984 // A dynamic exception specification is almost always "not noexcept",
4985 // with the exception that a pack expansion might expand to no types.
4986 case EST_Dynamic: {
4987 bool AnyPacks = false;
4988 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
4989 if (ET->getAs<PackExpansionType>())
4990 AnyPacks = true;
4991 ExceptionTypeStorage.push_back(getCanonicalType(ET));
4992 }
4993 if (!AnyPacks)
4994 CanonicalEPI.ExceptionSpec.Type = EST_None;
4995 else {
4996 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
4997 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
4998 }
4999 break;
5000 }
5001
5002 case EST_DynamicNone:
5003 case EST_BasicNoexcept:
5004 case EST_NoexceptTrue:
5005 case EST_NoThrow:
5006 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
5007 break;
5008
5010 llvm_unreachable("dependent noexcept is already canonical");
5011 }
5012 } else {
5013 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
5014 }
5015
5016 // Adjust the canonical function result type.
5017 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
5018 Canonical =
5019 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
5020
5021 // Get the new insert position for the node we care about.
5022 FunctionProtoType *NewIP =
5023 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
5024 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
5025 }
5026
5027 // Compute the needed size to hold this FunctionProtoType and the
5028 // various trailing objects.
5029 auto ESH = FunctionProtoType::getExceptionSpecSize(
5030 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
5031 size_t Size = FunctionProtoType::totalSizeToAlloc<
5032 QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields,
5033 FunctionType::FunctionTypeExtraAttributeInfo,
5034 FunctionType::FunctionTypeArmAttributes, FunctionType::ExceptionType,
5035 Expr *, FunctionDecl *, FunctionProtoType::ExtParameterInfo, Qualifiers,
5036 FunctionEffect, EffectConditionExpr>(
5039 EPI.requiresFunctionProtoTypeArmAttributes(), ESH.NumExceptionType,
5040 ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
5041 EPI.ExtParameterInfos ? NumArgs : 0,
5043 EPI.FunctionEffects.conditions().size());
5044
5045 auto *FTP = (FunctionProtoType *)Allocate(Size, alignof(FunctionProtoType));
5046 FunctionProtoType::ExtProtoInfo newEPI = EPI;
5047 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
5048 Types.push_back(FTP);
5049 if (!Unique)
5050 FunctionProtoTypes.InsertNode(FTP, InsertPos);
5051 if (!EPI.FunctionEffects.empty())
5052 AnyFunctionEffects = true;
5053 return QualType(FTP, 0);
5054}
5055
5056QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
5057 llvm::FoldingSetNodeID ID;
5058 PipeType::Profile(ID, T, ReadOnly);
5059
5060 void *InsertPos = nullptr;
5061 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
5062 return QualType(PT, 0);
5063
5064 // If the pipe element type isn't canonical, this won't be a canonical type
5065 // either, so fill in the canonical type field.
5066 QualType Canonical;
5067 if (!T.isCanonical()) {
5068 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
5069
5070 // Get the new insert position for the node we care about.
5071 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
5072 assert(!NewIP && "Shouldn't be in the map!");
5073 (void)NewIP;
5074 }
5075 auto *New = new (*this, alignof(PipeType)) PipeType(T, Canonical, ReadOnly);
5076 Types.push_back(New);
5077 PipeTypes.InsertNode(New, InsertPos);
5078 return QualType(New, 0);
5079}
5080
5082 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
5083 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
5084 : Ty;
5085}
5086
5088 return getPipeType(T, true);
5089}
5090
5092 return getPipeType(T, false);
5093}
5094
5095QualType ASTContext::getBitIntType(bool IsUnsigned, unsigned NumBits) const {
5096 llvm::FoldingSetNodeID ID;
5097 BitIntType::Profile(ID, IsUnsigned, NumBits);
5098
5099 void *InsertPos = nullptr;
5100 if (BitIntType *EIT = BitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
5101 return QualType(EIT, 0);
5102
5103 auto *New = new (*this, alignof(BitIntType)) BitIntType(IsUnsigned, NumBits);
5104 BitIntTypes.InsertNode(New, InsertPos);
5105 Types.push_back(New);
5106 return QualType(New, 0);
5107}
5108
5110 Expr *NumBitsExpr) const {
5111 assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent");
5112 llvm::FoldingSetNodeID ID;
5113 DependentBitIntType::Profile(ID, *this, IsUnsigned, NumBitsExpr);
5114
5115 void *InsertPos = nullptr;
5116 if (DependentBitIntType *Existing =
5117 DependentBitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
5118 return QualType(Existing, 0);
5119
5120 auto *New = new (*this, alignof(DependentBitIntType))
5121 DependentBitIntType(IsUnsigned, NumBitsExpr);
5122 DependentBitIntTypes.InsertNode(New, InsertPos);
5123
5124 Types.push_back(New);
5125 return QualType(New, 0);
5126}
5127
5130 using Kind = PredefinedSugarType::Kind;
5131
5132 if (auto *Target = PredefinedSugarTypes[llvm::to_underlying(KD)];
5133 Target != nullptr)
5134 return QualType(Target, 0);
5135
5136 auto getCanonicalType = [](const ASTContext &Ctx, Kind KDI) -> QualType {
5137 switch (KDI) {
5138 // size_t (C99TC3 6.5.3.4), signed size_t (C++23 5.13.2) and
5139 // ptrdiff_t (C99TC3 6.5.6) Although these types are not built-in, they
5140 // are part of the core language and are widely used. Using
5141 // PredefinedSugarType makes these types as named sugar types rather than
5142 // standard integer types, enabling better hints and diagnostics.
5143 case Kind::SizeT:
5144 return Ctx.getFromTargetType(Ctx.Target->getSizeType());
5145 case Kind::SignedSizeT:
5146 return Ctx.getFromTargetType(Ctx.Target->getSignedSizeType());
5147 case Kind::PtrdiffT:
5148 return Ctx.getFromTargetType(Ctx.Target->getPtrDiffType(LangAS::Default));
5149 }
5150 llvm_unreachable("unexpected kind");
5151 };
5152 auto *New = new (*this, alignof(PredefinedSugarType))
5153 PredefinedSugarType(KD, &Idents.get(PredefinedSugarType::getName(KD)),
5154 getCanonicalType(*this, static_cast<Kind>(KD)));
5155 Types.push_back(New);
5156 PredefinedSugarTypes[llvm::to_underlying(KD)] = New;
5157 return QualType(New, 0);
5158}
5159
5161 NestedNameSpecifier Qualifier,
5162 const TypeDecl *Decl) const {
5163 if (auto *Tag = dyn_cast<TagDecl>(Decl))
5164 return getTagType(Keyword, Qualifier, Tag,
5165 /*OwnsTag=*/false);
5166 if (auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
5167 return getTypedefType(Keyword, Qualifier, Typedef);
5168 if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(Decl))
5169 return getUnresolvedUsingType(Keyword, Qualifier, UD);
5170
5172 assert(!Qualifier);
5173 return QualType(Decl->TypeForDecl, 0);
5174}
5175
5177 if (auto *Tag = dyn_cast<TagDecl>(TD))
5178 return getCanonicalTagType(Tag);
5179 if (auto *TN = dyn_cast<TypedefNameDecl>(TD))
5180 return getCanonicalType(TN->getUnderlyingType());
5181 if (const auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(TD))
5183 assert(TD->TypeForDecl);
5184 return TD->TypeForDecl->getCanonicalTypeUnqualified();
5185}
5186
5188 if (const auto *TD = dyn_cast<TagDecl>(Decl))
5189 return getCanonicalTagType(TD);
5190 if (const auto *TD = dyn_cast<TypedefNameDecl>(Decl);
5191 isa_and_nonnull<TypedefDecl, TypeAliasDecl>(TD))
5193 /*Qualifier=*/std::nullopt, TD);
5194 if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl))
5195 return getCanonicalUnresolvedUsingType(Using);
5196
5197 assert(Decl->TypeForDecl);
5198 return QualType(Decl->TypeForDecl, 0);
5199}
5200
5201/// getTypedefType - Return the unique reference to the type for the
5202/// specified typedef name decl.
5205 NestedNameSpecifier Qualifier,
5206 const TypedefNameDecl *Decl, QualType UnderlyingType,
5207 std::optional<bool> TypeMatchesDeclOrNone) const {
5208 if (!TypeMatchesDeclOrNone) {
5209 QualType DeclUnderlyingType = Decl->getUnderlyingType();
5210 assert(!DeclUnderlyingType.isNull());
5211 if (UnderlyingType.isNull())
5212 UnderlyingType = DeclUnderlyingType;
5213 else
5214 assert(hasSameType(UnderlyingType, DeclUnderlyingType));
5215 TypeMatchesDeclOrNone = UnderlyingType == DeclUnderlyingType;
5216 } else {
5217 // FIXME: This is a workaround for a serialization cycle: assume the decl
5218 // underlying type is not available; don't touch it.
5219 assert(!UnderlyingType.isNull());
5220 }
5221
5222 if (Keyword == ElaboratedTypeKeyword::None && !Qualifier &&
5223 *TypeMatchesDeclOrNone) {
5224 if (Decl->TypeForDecl)
5225 return QualType(Decl->TypeForDecl, 0);
5226
5227 auto *NewType = new (*this, alignof(TypedefType))
5228 TypedefType(Type::Typedef, Keyword, Qualifier, Decl, UnderlyingType,
5229 !*TypeMatchesDeclOrNone);
5230
5231 Types.push_back(NewType);
5232 Decl->TypeForDecl = NewType;
5233 return QualType(NewType, 0);
5234 }
5235
5236 llvm::FoldingSetNodeID ID;
5237 TypedefType::Profile(ID, Keyword, Qualifier, Decl,
5238 *TypeMatchesDeclOrNone ? QualType() : UnderlyingType);
5239
5240 void *InsertPos = nullptr;
5241 if (FoldingSetPlaceholder<TypedefType> *Placeholder =
5242 TypedefTypes.FindNodeOrInsertPos(ID, InsertPos))
5243 return QualType(Placeholder->getType(), 0);
5244
5245 void *Mem =
5246 Allocate(TypedefType::totalSizeToAlloc<FoldingSetPlaceholder<TypedefType>,
5248 1, !!Qualifier, !*TypeMatchesDeclOrNone),
5249 alignof(TypedefType));
5250 auto *NewType =
5251 new (Mem) TypedefType(Type::Typedef, Keyword, Qualifier, Decl,
5252 UnderlyingType, !*TypeMatchesDeclOrNone);
5253 auto *Placeholder = new (NewType->getFoldingSetPlaceholder())
5255 TypedefTypes.InsertNode(Placeholder, InsertPos);
5256 Types.push_back(NewType);
5257 return QualType(NewType, 0);
5258}
5259
5261 NestedNameSpecifier Qualifier,
5262 const UsingShadowDecl *D,
5263 QualType UnderlyingType) const {
5264 // FIXME: This is expensive to compute every time!
5265 if (UnderlyingType.isNull()) {
5266 const auto *UD = cast<UsingDecl>(D->getIntroducer());
5267 UnderlyingType =
5270 UD->getQualifier(), cast<TypeDecl>(D->getTargetDecl()));
5271 }
5272
5273 llvm::FoldingSetNodeID ID;
5274 UsingType::Profile(ID, Keyword, Qualifier, D, UnderlyingType);
5275
5276 void *InsertPos = nullptr;
5277 if (const UsingType *T = UsingTypes.FindNodeOrInsertPos(ID, InsertPos))
5278 return QualType(T, 0);
5279
5280 assert(!UnderlyingType.hasLocalQualifiers());
5281
5282 assert(
5284 UnderlyingType));
5285
5286 void *Mem =
5287 Allocate(UsingType::totalSizeToAlloc<NestedNameSpecifier>(!!Qualifier),
5288 alignof(UsingType));
5289 UsingType *T = new (Mem) UsingType(Keyword, Qualifier, D, UnderlyingType);
5290 Types.push_back(T);
5291 UsingTypes.InsertNode(T, InsertPos);
5292 return QualType(T, 0);
5293}
5294
5295TagType *ASTContext::getTagTypeInternal(ElaboratedTypeKeyword Keyword,
5296 NestedNameSpecifier Qualifier,
5297 const TagDecl *TD, bool OwnsTag,
5298 bool IsInjected,
5299 const Type *CanonicalType,
5300 bool WithFoldingSetNode) const {
5301 auto [TC, Size] = [&] {
5302 switch (TD->getDeclKind()) {
5303 case Decl::Enum:
5304 static_assert(alignof(EnumType) == alignof(TagType));
5305 return std::make_tuple(Type::Enum, sizeof(EnumType));
5306 case Decl::ClassTemplatePartialSpecialization:
5307 case Decl::ClassTemplateSpecialization:
5308 case Decl::CXXRecord:
5309 static_assert(alignof(RecordType) == alignof(TagType));
5310 static_assert(alignof(InjectedClassNameType) == alignof(TagType));
5311 if (cast<CXXRecordDecl>(TD)->hasInjectedClassType())
5312 return std::make_tuple(Type::InjectedClassName,
5313 sizeof(InjectedClassNameType));
5314 [[fallthrough]];
5315 case Decl::Record:
5316 return std::make_tuple(Type::Record, sizeof(RecordType));
5317 default:
5318 llvm_unreachable("unexpected decl kind");
5319 }
5320 }();
5321
5322 if (Qualifier) {
5323 static_assert(alignof(NestedNameSpecifier) <= alignof(TagType));
5324 Size = llvm::alignTo(Size, alignof(NestedNameSpecifier)) +
5325 sizeof(NestedNameSpecifier);
5326 }
5327 void *Mem;
5328 if (WithFoldingSetNode) {
5329 // FIXME: It would be more profitable to tail allocate the folding set node
5330 // from the type, instead of the other way around, due to the greater
5331 // alignment requirements of the type. But this makes it harder to deal with
5332 // the different type node sizes. This would require either uniquing from
5333 // different folding sets, or having the folding setaccept a
5334 // contextual parameter which is not fixed at construction.
5335 Mem = Allocate(
5336 sizeof(TagTypeFoldingSetPlaceholder) +
5337 TagTypeFoldingSetPlaceholder::getOffset() + Size,
5338 std::max(alignof(TagTypeFoldingSetPlaceholder), alignof(TagType)));
5339 auto *T = new (Mem) TagTypeFoldingSetPlaceholder();
5340 Mem = T->getTagType();
5341 } else {
5342 Mem = Allocate(Size, alignof(TagType));
5343 }
5344
5345 auto *T = [&, TC = TC]() -> TagType * {
5346 switch (TC) {
5347 case Type::Enum: {
5348 assert(isa<EnumDecl>(TD));
5349 auto *T = new (Mem) EnumType(TC, Keyword, Qualifier, TD, OwnsTag,
5350 IsInjected, CanonicalType);
5351 assert(reinterpret_cast<void *>(T) ==
5352 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5353 "TagType must be the first base of EnumType");
5354 return T;
5355 }
5356 case Type::Record: {
5357 assert(isa<RecordDecl>(TD));
5358 auto *T = new (Mem) RecordType(TC, Keyword, Qualifier, TD, OwnsTag,
5359 IsInjected, CanonicalType);
5360 assert(reinterpret_cast<void *>(T) ==
5361 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5362 "TagType must be the first base of RecordType");
5363 return T;
5364 }
5365 case Type::InjectedClassName: {
5366 auto *T = new (Mem) InjectedClassNameType(Keyword, Qualifier, TD,
5367 IsInjected, CanonicalType);
5368 assert(reinterpret_cast<void *>(T) ==
5369 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5370 "TagType must be the first base of InjectedClassNameType");
5371 return T;
5372 }
5373 default:
5374 llvm_unreachable("unexpected type class");
5375 }
5376 }();
5377 assert(T->getKeyword() == Keyword);
5378 assert(T->getQualifier() == Qualifier);
5379 assert(T->getDecl() == TD);
5380 assert(T->isInjected() == IsInjected);
5381 assert(T->isTagOwned() == OwnsTag);
5382 assert((T->isCanonicalUnqualified()
5383 ? QualType()
5384 : T->getCanonicalTypeInternal()) == QualType(CanonicalType, 0));
5385 Types.push_back(T);
5386 return T;
5387}
5388
5389static const TagDecl *getNonInjectedClassName(const TagDecl *TD) {
5390 if (const auto *RD = dyn_cast<CXXRecordDecl>(TD);
5391 RD && RD->isInjectedClassName())
5392 return cast<TagDecl>(RD->getDeclContext());
5393 return TD;
5394}
5395
5398 if (TD->TypeForDecl)
5399 return TD->TypeForDecl->getCanonicalTypeUnqualified();
5400
5401 const Type *CanonicalType = getTagTypeInternal(
5403 /*Qualifier=*/std::nullopt, TD,
5404 /*OwnsTag=*/false, /*IsInjected=*/false, /*CanonicalType=*/nullptr,
5405 /*WithFoldingSetNode=*/false);
5406 TD->TypeForDecl = CanonicalType;
5407 return CanQualType::CreateUnsafe(QualType(CanonicalType, 0));
5408}
5409
5411 NestedNameSpecifier Qualifier,
5412 const TagDecl *TD, bool OwnsTag) const {
5413
5414 const TagDecl *NonInjectedTD = ::getNonInjectedClassName(TD);
5415 bool IsInjected = TD != NonInjectedTD;
5416
5417 ElaboratedTypeKeyword PreferredKeyword =
5420 NonInjectedTD->getTagKind());
5421
5422 if (Keyword == PreferredKeyword && !Qualifier && !OwnsTag) {
5423 if (const Type *T = TD->TypeForDecl; T && !T->isCanonicalUnqualified())
5424 return QualType(T, 0);
5425
5426 const Type *CanonicalType = getCanonicalTagType(NonInjectedTD).getTypePtr();
5427 const Type *T =
5428 getTagTypeInternal(Keyword,
5429 /*Qualifier=*/std::nullopt, NonInjectedTD,
5430 /*OwnsTag=*/false, IsInjected, CanonicalType,
5431 /*WithFoldingSetNode=*/false);
5432 TD->TypeForDecl = T;
5433 return QualType(T, 0);
5434 }
5435
5436 llvm::FoldingSetNodeID ID;
5437 TagTypeFoldingSetPlaceholder::Profile(ID, Keyword, Qualifier, NonInjectedTD,
5438 OwnsTag, IsInjected);
5439
5440 void *InsertPos = nullptr;
5441 if (TagTypeFoldingSetPlaceholder *T =
5442 TagTypes.FindNodeOrInsertPos(ID, InsertPos))
5443 return QualType(T->getTagType(), 0);
5444
5445 const Type *CanonicalType = getCanonicalTagType(NonInjectedTD).getTypePtr();
5446 TagType *T =
5447 getTagTypeInternal(Keyword, Qualifier, NonInjectedTD, OwnsTag, IsInjected,
5448 CanonicalType, /*WithFoldingSetNode=*/true);
5449 TagTypes.InsertNode(TagTypeFoldingSetPlaceholder::fromTagType(T), InsertPos);
5450 return QualType(T, 0);
5451}
5452
5453bool ASTContext::computeBestEnumTypes(bool IsPacked, unsigned NumNegativeBits,
5454 unsigned NumPositiveBits,
5455 QualType &BestType,
5456 QualType &BestPromotionType) {
5457 unsigned IntWidth = Target->getIntWidth();
5458 unsigned CharWidth = Target->getCharWidth();
5459 unsigned ShortWidth = Target->getShortWidth();
5460 bool EnumTooLarge = false;
5461 unsigned BestWidth;
5462 if (NumNegativeBits) {
5463 // If there is a negative value, figure out the smallest integer type (of
5464 // int/long/longlong) that fits.
5465 // If it's packed, check also if it fits a char or a short.
5466 if (IsPacked && NumNegativeBits <= CharWidth &&
5467 NumPositiveBits < CharWidth) {
5468 BestType = SignedCharTy;
5469 BestWidth = CharWidth;
5470 } else if (IsPacked && NumNegativeBits <= ShortWidth &&
5471 NumPositiveBits < ShortWidth) {
5472 BestType = ShortTy;
5473 BestWidth = ShortWidth;
5474 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
5475 BestType = IntTy;
5476 BestWidth = IntWidth;
5477 } else {
5478 BestWidth = Target->getLongWidth();
5479
5480 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
5481 BestType = LongTy;
5482 } else {
5483 BestWidth = Target->getLongLongWidth();
5484
5485 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
5486 EnumTooLarge = true;
5487 BestType = LongLongTy;
5488 }
5489 }
5490 BestPromotionType = (BestWidth <= IntWidth ? IntTy : BestType);
5491 } else {
5492 // If there is no negative value, figure out the smallest type that fits
5493 // all of the enumerator values.
5494 // If it's packed, check also if it fits a char or a short.
5495 if (IsPacked && NumPositiveBits <= CharWidth) {
5496 BestType = UnsignedCharTy;
5497 BestPromotionType = IntTy;
5498 BestWidth = CharWidth;
5499 } else if (IsPacked && NumPositiveBits <= ShortWidth) {
5500 BestType = UnsignedShortTy;
5501 BestPromotionType = IntTy;
5502 BestWidth = ShortWidth;
5503 } else if (NumPositiveBits <= IntWidth) {
5504 BestType = UnsignedIntTy;
5505 BestWidth = IntWidth;
5506 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5508 : IntTy;
5509 } else if (NumPositiveBits <= (BestWidth = Target->getLongWidth())) {
5510 BestType = UnsignedLongTy;
5511 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5513 : LongTy;
5514 } else {
5515 BestWidth = Target->getLongLongWidth();
5516 if (NumPositiveBits > BestWidth) {
5517 // This can happen with bit-precise integer types, but those are not
5518 // allowed as the type for an enumerator per C23 6.7.2.2p4 and p12.
5519 // FIXME: GCC uses __int128_t and __uint128_t for cases that fit within
5520 // a 128-bit integer, we should consider doing the same.
5521 EnumTooLarge = true;
5522 }
5523 BestType = UnsignedLongLongTy;
5524 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5526 : LongLongTy;
5527 }
5528 }
5529 return EnumTooLarge;
5530}
5531
5533 assert((T->isIntegralType(*this) || T->isEnumeralType()) &&
5534 "Integral type required!");
5535 unsigned BitWidth = getIntWidth(T);
5536
5537 if (Value.isUnsigned() || Value.isNonNegative()) {
5538 if (T->isSignedIntegerOrEnumerationType())
5539 --BitWidth;
5540 return Value.getActiveBits() <= BitWidth;
5541 }
5542 return Value.getSignificantBits() <= BitWidth;
5543}
5544
5545UnresolvedUsingType *ASTContext::getUnresolvedUsingTypeInternal(
5547 const UnresolvedUsingTypenameDecl *D, void *InsertPos,
5548 const Type *CanonicalType) const {
5549 void *Mem = Allocate(
5550 UnresolvedUsingType::totalSizeToAlloc<
5552 !!InsertPos, !!Qualifier),
5553 alignof(UnresolvedUsingType));
5554 auto *T = new (Mem) UnresolvedUsingType(Keyword, Qualifier, D, CanonicalType);
5555 if (InsertPos) {
5556 auto *Placeholder = new (T->getFoldingSetPlaceholder())
5558 TypedefTypes.InsertNode(Placeholder, InsertPos);
5559 }
5560 Types.push_back(T);
5561 return T;
5562}
5563
5565 const UnresolvedUsingTypenameDecl *D) const {
5566 D = D->getCanonicalDecl();
5567 if (D->TypeForDecl)
5568 return D->TypeForDecl->getCanonicalTypeUnqualified();
5569
5570 const Type *CanonicalType = getUnresolvedUsingTypeInternal(
5572 /*Qualifier=*/std::nullopt, D,
5573 /*InsertPos=*/nullptr, /*CanonicalType=*/nullptr);
5574 D->TypeForDecl = CanonicalType;
5575 return CanQualType::CreateUnsafe(QualType(CanonicalType, 0));
5576}
5577
5580 NestedNameSpecifier Qualifier,
5581 const UnresolvedUsingTypenameDecl *D) const {
5582 if (Keyword == ElaboratedTypeKeyword::None && !Qualifier) {
5583 if (const Type *T = D->TypeForDecl; T && !T->isCanonicalUnqualified())
5584 return QualType(T, 0);
5585
5586 const Type *CanonicalType = getCanonicalUnresolvedUsingType(D).getTypePtr();
5587 const Type *T =
5588 getUnresolvedUsingTypeInternal(ElaboratedTypeKeyword::None,
5589 /*Qualifier=*/std::nullopt, D,
5590 /*InsertPos=*/nullptr, CanonicalType);
5591 D->TypeForDecl = T;
5592 return QualType(T, 0);
5593 }
5594
5595 llvm::FoldingSetNodeID ID;
5596 UnresolvedUsingType::Profile(ID, Keyword, Qualifier, D);
5597
5598 void *InsertPos = nullptr;
5600 UnresolvedUsingTypes.FindNodeOrInsertPos(ID, InsertPos))
5601 return QualType(Placeholder->getType(), 0);
5602 assert(InsertPos);
5603
5604 const Type *CanonicalType = getCanonicalUnresolvedUsingType(D).getTypePtr();
5605 const Type *T = getUnresolvedUsingTypeInternal(Keyword, Qualifier, D,
5606 InsertPos, CanonicalType);
5607 return QualType(T, 0);
5608}
5609
5611 QualType modifiedType,
5612 QualType equivalentType,
5613 const Attr *attr) const {
5614 llvm::FoldingSetNodeID id;
5615 AttributedType::Profile(id, attrKind, modifiedType, equivalentType, attr);
5616
5617 void *insertPos = nullptr;
5618 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
5619 if (type) return QualType(type, 0);
5620
5621 assert(!attr || attr->getKind() == attrKind);
5622
5623 QualType canon = getCanonicalType(equivalentType);
5624 type = new (*this, alignof(AttributedType))
5625 AttributedType(canon, attrKind, attr, modifiedType, equivalentType);
5626
5627 Types.push_back(type);
5628 AttributedTypes.InsertNode(type, insertPos);
5629
5630 return QualType(type, 0);
5631}
5632
5634 QualType equivalentType) const {
5635 return getAttributedType(attr->getKind(), modifiedType, equivalentType, attr);
5636}
5637
5639 QualType modifiedType,
5640 QualType equivalentType) {
5641 switch (nullability) {
5643 return getAttributedType(attr::TypeNonNull, modifiedType, equivalentType);
5644
5646 return getAttributedType(attr::TypeNullable, modifiedType, equivalentType);
5647
5649 return getAttributedType(attr::TypeNullableResult, modifiedType,
5650 equivalentType);
5651
5653 return getAttributedType(attr::TypeNullUnspecified, modifiedType,
5654 equivalentType);
5655 }
5656
5657 llvm_unreachable("Unknown nullability kind");
5658}
5659
5660QualType ASTContext::getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
5661 QualType Wrapped) const {
5662 llvm::FoldingSetNodeID ID;
5663 BTFTagAttributedType::Profile(ID, Wrapped, BTFAttr);
5664
5665 void *InsertPos = nullptr;
5666 BTFTagAttributedType *Ty =
5667 BTFTagAttributedTypes.FindNodeOrInsertPos(ID, InsertPos);
5668 if (Ty)
5669 return QualType(Ty, 0);
5670
5671 QualType Canon = getCanonicalType(Wrapped);
5672 Ty = new (*this, alignof(BTFTagAttributedType))
5673 BTFTagAttributedType(Canon, Wrapped, BTFAttr);
5674
5675 Types.push_back(Ty);
5676 BTFTagAttributedTypes.InsertNode(Ty, InsertPos);
5677
5678 return QualType(Ty, 0);
5679}
5680
5682 QualType Wrapped, QualType Contained,
5683 const HLSLAttributedResourceType::Attributes &Attrs) {
5684
5685 llvm::FoldingSetNodeID ID;
5686 HLSLAttributedResourceType::Profile(ID, Wrapped, Contained, Attrs);
5687
5688 void *InsertPos = nullptr;
5689 HLSLAttributedResourceType *Ty =
5690 HLSLAttributedResourceTypes.FindNodeOrInsertPos(ID, InsertPos);
5691 if (Ty)
5692 return QualType(Ty, 0);
5693
5694 Ty = new (*this, alignof(HLSLAttributedResourceType))
5695 HLSLAttributedResourceType(Wrapped, Contained, Attrs);
5696
5697 Types.push_back(Ty);
5698 HLSLAttributedResourceTypes.InsertNode(Ty, InsertPos);
5699
5700 return QualType(Ty, 0);
5701}
5702
5703QualType ASTContext::getHLSLInlineSpirvType(uint32_t Opcode, uint32_t Size,
5704 uint32_t Alignment,
5705 ArrayRef<SpirvOperand> Operands) {
5706 llvm::FoldingSetNodeID ID;
5707 HLSLInlineSpirvType::Profile(ID, Opcode, Size, Alignment, Operands);
5708
5709 void *InsertPos = nullptr;
5710 HLSLInlineSpirvType *Ty =
5711 HLSLInlineSpirvTypes.FindNodeOrInsertPos(ID, InsertPos);
5712 if (Ty)
5713 return QualType(Ty, 0);
5714
5715 void *Mem = Allocate(
5716 HLSLInlineSpirvType::totalSizeToAlloc<SpirvOperand>(Operands.size()),
5717 alignof(HLSLInlineSpirvType));
5718
5719 Ty = new (Mem) HLSLInlineSpirvType(Opcode, Size, Alignment, Operands);
5720
5721 Types.push_back(Ty);
5722 HLSLInlineSpirvTypes.InsertNode(Ty, InsertPos);
5723
5724 return QualType(Ty, 0);
5725}
5726
5727/// Retrieve a substitution-result type.
5729 Decl *AssociatedDecl,
5730 unsigned Index,
5731 UnsignedOrNone PackIndex,
5732 bool Final) const {
5733 llvm::FoldingSetNodeID ID;
5734 SubstTemplateTypeParmType::Profile(ID, Replacement, AssociatedDecl, Index,
5735 PackIndex, Final);
5736 void *InsertPos = nullptr;
5737 SubstTemplateTypeParmType *SubstParm =
5738 SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
5739
5740 if (!SubstParm) {
5741 void *Mem = Allocate(SubstTemplateTypeParmType::totalSizeToAlloc<QualType>(
5742 !Replacement.isCanonical()),
5743 alignof(SubstTemplateTypeParmType));
5744 SubstParm = new (Mem) SubstTemplateTypeParmType(Replacement, AssociatedDecl,
5745 Index, PackIndex, Final);
5746 Types.push_back(SubstParm);
5747 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
5748 }
5749
5750 return QualType(SubstParm, 0);
5751}
5752
5755 unsigned Index, bool Final,
5756 const TemplateArgument &ArgPack) {
5757#ifndef NDEBUG
5758 for (const auto &P : ArgPack.pack_elements())
5759 assert(P.getKind() == TemplateArgument::Type && "Pack contains a non-type");
5760#endif
5761
5762 llvm::FoldingSetNodeID ID;
5763 SubstTemplateTypeParmPackType::Profile(ID, AssociatedDecl, Index, Final,
5764 ArgPack);
5765 void *InsertPos = nullptr;
5766 if (SubstTemplateTypeParmPackType *SubstParm =
5767 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
5768 return QualType(SubstParm, 0);
5769
5770 QualType Canon;
5771 {
5772 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(ArgPack);
5773 if (!AssociatedDecl->isCanonicalDecl() ||
5774 !CanonArgPack.structurallyEquals(ArgPack)) {
5776 AssociatedDecl->getCanonicalDecl(), Index, Final, CanonArgPack);
5777 [[maybe_unused]] const auto *Nothing =
5778 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
5779 assert(!Nothing);
5780 }
5781 }
5782
5783 auto *SubstParm = new (*this, alignof(SubstTemplateTypeParmPackType))
5784 SubstTemplateTypeParmPackType(Canon, AssociatedDecl, Index, Final,
5785 ArgPack);
5786 Types.push_back(SubstParm);
5787 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
5788 return QualType(SubstParm, 0);
5789}
5790
5793 assert(llvm::all_of(ArgPack.pack_elements(),
5794 [](const auto &P) {
5795 return P.getKind() == TemplateArgument::Type;
5796 }) &&
5797 "Pack contains a non-type");
5798
5799 llvm::FoldingSetNodeID ID;
5800 SubstBuiltinTemplatePackType::Profile(ID, ArgPack);
5801
5802 void *InsertPos = nullptr;
5803 if (auto *T =
5804 SubstBuiltinTemplatePackTypes.FindNodeOrInsertPos(ID, InsertPos))
5805 return QualType(T, 0);
5806
5807 QualType Canon;
5808 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(ArgPack);
5809 if (!CanonArgPack.structurallyEquals(ArgPack)) {
5810 Canon = getSubstBuiltinTemplatePack(CanonArgPack);
5811 // Refresh InsertPos, in case the recursive call above caused rehashing,
5812 // which would invalidate the bucket pointer.
5813 [[maybe_unused]] const auto *Nothing =
5814 SubstBuiltinTemplatePackTypes.FindNodeOrInsertPos(ID, InsertPos);
5815 assert(!Nothing);
5816 }
5817
5818 auto *PackType = new (*this, alignof(SubstBuiltinTemplatePackType))
5819 SubstBuiltinTemplatePackType(Canon, ArgPack);
5820 Types.push_back(PackType);
5821 SubstBuiltinTemplatePackTypes.InsertNode(PackType, InsertPos);
5822 return QualType(PackType, 0);
5823}
5824
5825/// Retrieve the template type parameter type for a template
5826/// parameter or parameter pack with the given depth, index, and (optionally)
5827/// name.
5828QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
5829 bool ParameterPack,
5830 TemplateTypeParmDecl *TTPDecl) const {
5831 llvm::FoldingSetNodeID ID;
5832 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
5833 void *InsertPos = nullptr;
5834 TemplateTypeParmType *TypeParm
5835 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
5836
5837 if (TypeParm)
5838 return QualType(TypeParm, 0);
5839
5840 if (TTPDecl) {
5841 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
5842 TypeParm = new (*this, alignof(TemplateTypeParmType))
5843 TemplateTypeParmType(Depth, Index, ParameterPack, TTPDecl, Canon);
5844
5845 TemplateTypeParmType *TypeCheck
5846 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
5847 assert(!TypeCheck && "Template type parameter canonical type broken");
5848 (void)TypeCheck;
5849 } else
5850 TypeParm = new (*this, alignof(TemplateTypeParmType)) TemplateTypeParmType(
5851 Depth, Index, ParameterPack, /*TTPDecl=*/nullptr, /*Canon=*/QualType());
5852
5853 Types.push_back(TypeParm);
5854 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
5855
5856 return QualType(TypeParm, 0);
5857}
5858
5861 switch (Keyword) {
5862 // These are just themselves.
5868 return Keyword;
5869
5870 // These are equivalent.
5873
5874 // These are functionally equivalent, so relying on their equivalence is
5875 // IFNDR. By making them equivalent, we disallow overloading, which at least
5876 // can produce a diagnostic.
5879 }
5880 llvm_unreachable("unexpected keyword kind");
5881}
5882
5884 ElaboratedTypeKeyword Keyword, SourceLocation ElaboratedKeywordLoc,
5885 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKeywordLoc,
5886 TemplateName Name, SourceLocation NameLoc,
5887 const TemplateArgumentListInfo &SpecifiedArgs,
5888 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
5890 Keyword, Name, SpecifiedArgs.arguments(), CanonicalArgs, Underlying);
5891
5894 ElaboratedKeywordLoc, QualifierLoc, TemplateKeywordLoc, NameLoc,
5895 SpecifiedArgs);
5896 return DI;
5897}
5898
5901 ArrayRef<TemplateArgumentLoc> SpecifiedArgs,
5902 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
5903 SmallVector<TemplateArgument, 4> SpecifiedArgVec;
5904 SpecifiedArgVec.reserve(SpecifiedArgs.size());
5905 for (const TemplateArgumentLoc &Arg : SpecifiedArgs)
5906 SpecifiedArgVec.push_back(Arg.getArgument());
5907
5908 return getTemplateSpecializationType(Keyword, Template, SpecifiedArgVec,
5909 CanonicalArgs, Underlying);
5910}
5911
5912[[maybe_unused]] static bool
5914 for (const TemplateArgument &Arg : Args)
5915 if (Arg.isPackExpansion())
5916 return true;
5917 return false;
5918}
5919
5922 ArrayRef<TemplateArgument> Args) const {
5923 assert(Template ==
5924 getCanonicalTemplateName(Template, /*IgnoreDeduced=*/true));
5926 Template.getAsDependentTemplateName()));
5927#ifndef NDEBUG
5928 for (const auto &Arg : Args)
5929 assert(Arg.structurallyEquals(getCanonicalTemplateArgument(Arg)));
5930#endif
5931
5932 llvm::FoldingSetNodeID ID;
5933 TemplateSpecializationType::Profile(ID, Keyword, Template, Args, QualType(),
5934 *this);
5935 void *InsertPos = nullptr;
5936 if (auto *T = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
5937 return QualType(T, 0);
5938
5939 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
5940 sizeof(TemplateArgument) * Args.size(),
5941 alignof(TemplateSpecializationType));
5942 auto *Spec =
5943 new (Mem) TemplateSpecializationType(Keyword, Template,
5944 /*IsAlias=*/false, Args, QualType());
5945 assert(Spec->isDependentType() &&
5946 "canonical template specialization must be dependent");
5947 Types.push_back(Spec);
5948 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
5949 return QualType(Spec, 0);
5950}
5951
5954 ArrayRef<TemplateArgument> SpecifiedArgs,
5955 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
5956 const auto *TD = Template.getAsTemplateDecl(/*IgnoreDeduced=*/true);
5957 bool IsTypeAlias = TD && TD->isTypeAlias();
5958 if (Underlying.isNull()) {
5959 TemplateName CanonTemplate =
5960 getCanonicalTemplateName(Template, /*IgnoreDeduced=*/true);
5961 ElaboratedTypeKeyword CanonKeyword =
5962 CanonTemplate.getAsDependentTemplateName()
5965 bool NonCanonical = Template != CanonTemplate || Keyword != CanonKeyword;
5967 if (CanonicalArgs.empty()) {
5968 CanonArgsVec = SmallVector<TemplateArgument, 4>(SpecifiedArgs);
5969 NonCanonical |= canonicalizeTemplateArguments(CanonArgsVec);
5970 CanonicalArgs = CanonArgsVec;
5971 } else {
5972 NonCanonical |= !llvm::equal(
5973 SpecifiedArgs, CanonicalArgs,
5974 [](const TemplateArgument &A, const TemplateArgument &B) {
5975 return A.structurallyEquals(B);
5976 });
5977 }
5978
5979 // We can get here with an alias template when the specialization
5980 // contains a pack expansion that does not match up with a parameter
5981 // pack, or a builtin template which cannot be resolved due to dependency.
5982 assert((!isa_and_nonnull<TypeAliasTemplateDecl>(TD) ||
5983 hasAnyPackExpansions(CanonicalArgs)) &&
5984 "Caller must compute aliased type");
5985 IsTypeAlias = false;
5986
5988 CanonKeyword, CanonTemplate, CanonicalArgs);
5989 if (!NonCanonical)
5990 return Underlying;
5991 }
5992 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
5993 sizeof(TemplateArgument) * SpecifiedArgs.size() +
5994 (IsTypeAlias ? sizeof(QualType) : 0),
5995 alignof(TemplateSpecializationType));
5996 auto *Spec = new (Mem) TemplateSpecializationType(
5997 Keyword, Template, IsTypeAlias, SpecifiedArgs, Underlying);
5998 Types.push_back(Spec);
5999 return QualType(Spec, 0);
6000}
6001
6004 llvm::FoldingSetNodeID ID;
6005 ParenType::Profile(ID, InnerType);
6006
6007 void *InsertPos = nullptr;
6008 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
6009 if (T)
6010 return QualType(T, 0);
6011
6012 QualType Canon = InnerType;
6013 if (!Canon.isCanonical()) {
6014 Canon = getCanonicalType(InnerType);
6015 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
6016 assert(!CheckT && "Paren canonical type broken");
6017 (void)CheckT;
6018 }
6019
6020 T = new (*this, alignof(ParenType)) ParenType(InnerType, Canon);
6021 Types.push_back(T);
6022 ParenTypes.InsertNode(T, InsertPos);
6023 return QualType(T, 0);
6024}
6025
6028 const IdentifierInfo *MacroII) const {
6029 QualType Canon = UnderlyingTy;
6030 if (!Canon.isCanonical())
6031 Canon = getCanonicalType(UnderlyingTy);
6032
6033 auto *newType = new (*this, alignof(MacroQualifiedType))
6034 MacroQualifiedType(UnderlyingTy, Canon, MacroII);
6035 Types.push_back(newType);
6036 return QualType(newType, 0);
6037}
6038
6041 const IdentifierInfo *Name) const {
6042 llvm::FoldingSetNodeID ID;
6043 DependentNameType::Profile(ID, Keyword, NNS, Name);
6044
6045 void *InsertPos = nullptr;
6046 if (DependentNameType *T =
6047 DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos))
6048 return QualType(T, 0);
6049
6050 ElaboratedTypeKeyword CanonKeyword =
6052 NestedNameSpecifier CanonNNS = NNS.getCanonical();
6053
6054 QualType Canon;
6055 if (CanonKeyword != Keyword || CanonNNS != NNS) {
6056 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
6057 [[maybe_unused]] DependentNameType *T =
6058 DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
6059 assert(!T && "broken canonicalization");
6060 assert(Canon.isCanonical());
6061 }
6062
6063 DependentNameType *T = new (*this, alignof(DependentNameType))
6064 DependentNameType(Keyword, NNS, Name, Canon);
6065 Types.push_back(T);
6066 DependentNameTypes.InsertNode(T, InsertPos);
6067 return QualType(T, 0);
6068}
6069
6071 TemplateArgument Arg;
6072 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
6074 if (TTP->isParameterPack())
6075 ArgType = getPackExpansionType(ArgType, std::nullopt);
6076
6078 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
6079 QualType T =
6080 NTTP->getType().getNonPackExpansionType().getNonLValueExprType(*this);
6081 // For class NTTPs, ensure we include the 'const' so the type matches that
6082 // of a real template argument.
6083 // FIXME: It would be more faithful to model this as something like an
6084 // lvalue-to-rvalue conversion applied to a const-qualified lvalue.
6086 if (T->isRecordType()) {
6087 // C++ [temp.param]p8: An id-expression naming a non-type
6088 // template-parameter of class type T denotes a static storage duration
6089 // object of type const T.
6090 T.addConst();
6091 VK = VK_LValue;
6092 } else {
6093 VK = Expr::getValueKindForType(NTTP->getType());
6094 }
6095 Expr *E = new (*this)
6096 DeclRefExpr(*this, NTTP, /*RefersToEnclosingVariableOrCapture=*/false,
6097 T, VK, NTTP->getLocation());
6098
6099 if (NTTP->isParameterPack())
6100 E = new (*this) PackExpansionExpr(E, NTTP->getLocation(), std::nullopt);
6101 Arg = TemplateArgument(E, /*IsCanonical=*/false);
6102 } else {
6103 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
6105 /*Qualifier=*/std::nullopt, /*TemplateKeyword=*/false,
6106 TemplateName(TTP));
6107 if (TTP->isParameterPack())
6108 Arg = TemplateArgument(Name, /*NumExpansions=*/std::nullopt);
6109 else
6110 Arg = TemplateArgument(Name);
6111 }
6112
6113 if (Param->isTemplateParameterPack())
6114 Arg =
6115 TemplateArgument::CreatePackCopy(const_cast<ASTContext &>(*this), Arg);
6116
6117 return Arg;
6118}
6119
6121 UnsignedOrNone NumExpansions,
6122 bool ExpectPackInType) const {
6123 assert((!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) &&
6124 "Pack expansions must expand one or more parameter packs");
6125
6126 llvm::FoldingSetNodeID ID;
6127 PackExpansionType::Profile(ID, Pattern, NumExpansions);
6128
6129 void *InsertPos = nullptr;
6130 PackExpansionType *T = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
6131 if (T)
6132 return QualType(T, 0);
6133
6134 QualType Canon;
6135 if (!Pattern.isCanonical()) {
6136 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions,
6137 /*ExpectPackInType=*/false);
6138
6139 // Find the insert position again, in case we inserted an element into
6140 // PackExpansionTypes and invalidated our insert position.
6141 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
6142 }
6143
6144 T = new (*this, alignof(PackExpansionType))
6145 PackExpansionType(Pattern, Canon, NumExpansions);
6146 Types.push_back(T);
6147 PackExpansionTypes.InsertNode(T, InsertPos);
6148 return QualType(T, 0);
6149}
6150
6151/// CmpProtocolNames - Comparison predicate for sorting protocols
6152/// alphabetically.
6153static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
6154 ObjCProtocolDecl *const *RHS) {
6155 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
6156}
6157
6159 if (Protocols.empty()) return true;
6160
6161 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
6162 return false;
6163
6164 for (unsigned i = 1; i != Protocols.size(); ++i)
6165 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
6166 Protocols[i]->getCanonicalDecl() != Protocols[i])
6167 return false;
6168 return true;
6169}
6170
6171static void
6173 // Sort protocols, keyed by name.
6174 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
6175
6176 // Canonicalize.
6177 for (ObjCProtocolDecl *&P : Protocols)
6178 P = P->getCanonicalDecl();
6179
6180 // Remove duplicates.
6181 auto ProtocolsEnd = llvm::unique(Protocols);
6182 Protocols.erase(ProtocolsEnd, Protocols.end());
6183}
6184
6186 ObjCProtocolDecl * const *Protocols,
6187 unsigned NumProtocols) const {
6188 return getObjCObjectType(BaseType, {}, ArrayRef(Protocols, NumProtocols),
6189 /*isKindOf=*/false);
6190}
6191
6193 QualType baseType,
6194 ArrayRef<QualType> typeArgs,
6196 bool isKindOf) const {
6197 // If the base type is an interface and there aren't any protocols or
6198 // type arguments to add, then the interface type will do just fine.
6199 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
6200 isa<ObjCInterfaceType>(baseType))
6201 return baseType;
6202
6203 // Look in the folding set for an existing type.
6204 llvm::FoldingSetNodeID ID;
6205 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
6206 void *InsertPos = nullptr;
6207 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
6208 return QualType(QT, 0);
6209
6210 // Determine the type arguments to be used for canonicalization,
6211 // which may be explicitly specified here or written on the base
6212 // type.
6213 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
6214 if (effectiveTypeArgs.empty()) {
6215 if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
6216 effectiveTypeArgs = baseObject->getTypeArgs();
6217 }
6218
6219 // Build the canonical type, which has the canonical base type and a
6220 // sorted-and-uniqued list of protocols and the type arguments
6221 // canonicalized.
6222 QualType canonical;
6223 bool typeArgsAreCanonical = llvm::all_of(
6224 effectiveTypeArgs, [&](QualType type) { return type.isCanonical(); });
6225 bool protocolsSorted = areSortedAndUniqued(protocols);
6226 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
6227 // Determine the canonical type arguments.
6228 ArrayRef<QualType> canonTypeArgs;
6229 SmallVector<QualType, 4> canonTypeArgsVec;
6230 if (!typeArgsAreCanonical) {
6231 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
6232 for (auto typeArg : effectiveTypeArgs)
6233 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
6234 canonTypeArgs = canonTypeArgsVec;
6235 } else {
6236 canonTypeArgs = effectiveTypeArgs;
6237 }
6238
6239 ArrayRef<ObjCProtocolDecl *> canonProtocols;
6240 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
6241 if (!protocolsSorted) {
6242 canonProtocolsVec.append(protocols.begin(), protocols.end());
6243 SortAndUniqueProtocols(canonProtocolsVec);
6244 canonProtocols = canonProtocolsVec;
6245 } else {
6246 canonProtocols = protocols;
6247 }
6248
6249 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
6250 canonProtocols, isKindOf);
6251
6252 // Regenerate InsertPos.
6253 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
6254 }
6255
6256 unsigned size = sizeof(ObjCObjectTypeImpl);
6257 size += typeArgs.size() * sizeof(QualType);
6258 size += protocols.size() * sizeof(ObjCProtocolDecl *);
6259 void *mem = Allocate(size, alignof(ObjCObjectTypeImpl));
6260 auto *T =
6261 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
6262 isKindOf);
6263
6264 Types.push_back(T);
6265 ObjCObjectTypes.InsertNode(T, InsertPos);
6266 return QualType(T, 0);
6267}
6268
6269/// Apply Objective-C protocol qualifiers to the given type.
6270/// If this is for the canonical type of a type parameter, we can apply
6271/// protocol qualifiers on the ObjCObjectPointerType.
6274 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
6275 bool allowOnPointerType) const {
6276 hasError = false;
6277
6278 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
6279 return getObjCTypeParamType(objT->getDecl(), protocols);
6280 }
6281
6282 // Apply protocol qualifiers to ObjCObjectPointerType.
6283 if (allowOnPointerType) {
6284 if (const auto *objPtr =
6285 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
6286 const ObjCObjectType *objT = objPtr->getObjectType();
6287 // Merge protocol lists and construct ObjCObjectType.
6289 protocolsVec.append(objT->qual_begin(),
6290 objT->qual_end());
6291 protocolsVec.append(protocols.begin(), protocols.end());
6292 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
6294 objT->getBaseType(),
6295 objT->getTypeArgsAsWritten(),
6296 protocols,
6297 objT->isKindOfTypeAsWritten());
6299 }
6300 }
6301
6302 // Apply protocol qualifiers to ObjCObjectType.
6303 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
6304 // FIXME: Check for protocols to which the class type is already
6305 // known to conform.
6306
6307 return getObjCObjectType(objT->getBaseType(),
6308 objT->getTypeArgsAsWritten(),
6309 protocols,
6310 objT->isKindOfTypeAsWritten());
6311 }
6312
6313 // If the canonical type is ObjCObjectType, ...
6314 if (type->isObjCObjectType()) {
6315 // Silently overwrite any existing protocol qualifiers.
6316 // TODO: determine whether that's the right thing to do.
6317
6318 // FIXME: Check for protocols to which the class type is already
6319 // known to conform.
6320 return getObjCObjectType(type, {}, protocols, false);
6321 }
6322
6323 // id<protocol-list>
6324 if (type->isObjCIdType()) {
6325 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6326 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
6327 objPtr->isKindOfType());
6329 }
6330
6331 // Class<protocol-list>
6332 if (type->isObjCClassType()) {
6333 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6334 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
6335 objPtr->isKindOfType());
6337 }
6338
6339 hasError = true;
6340 return type;
6341}
6342
6345 ArrayRef<ObjCProtocolDecl *> protocols) const {
6346 // Look in the folding set for an existing type.
6347 llvm::FoldingSetNodeID ID;
6348 ObjCTypeParamType::Profile(ID, Decl, Decl->getUnderlyingType(), protocols);
6349 void *InsertPos = nullptr;
6350 if (ObjCTypeParamType *TypeParam =
6351 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
6352 return QualType(TypeParam, 0);
6353
6354 // We canonicalize to the underlying type.
6355 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
6356 if (!protocols.empty()) {
6357 // Apply the protocol qualifers.
6358 bool hasError;
6360 Canonical, protocols, hasError, true /*allowOnPointerType*/));
6361 assert(!hasError && "Error when apply protocol qualifier to bound type");
6362 }
6363
6364 unsigned size = sizeof(ObjCTypeParamType);
6365 size += protocols.size() * sizeof(ObjCProtocolDecl *);
6366 void *mem = Allocate(size, alignof(ObjCTypeParamType));
6367 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
6368
6369 Types.push_back(newType);
6370 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
6371 return QualType(newType, 0);
6372}
6373
6375 ObjCTypeParamDecl *New) const {
6376 New->setTypeSourceInfo(getTrivialTypeSourceInfo(Orig->getUnderlyingType()));
6377 // Update TypeForDecl after updating TypeSourceInfo.
6378 auto *NewTypeParamTy = cast<ObjCTypeParamType>(New->TypeForDecl);
6380 protocols.append(NewTypeParamTy->qual_begin(), NewTypeParamTy->qual_end());
6381 QualType UpdatedTy = getObjCTypeParamType(New, protocols);
6382 New->TypeForDecl = UpdatedTy.getTypePtr();
6383}
6384
6385/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
6386/// protocol list adopt all protocols in QT's qualified-id protocol
6387/// list.
6389 ObjCInterfaceDecl *IC) {
6390 if (!QT->isObjCQualifiedIdType())
6391 return false;
6392
6393 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
6394 // If both the right and left sides have qualifiers.
6395 for (auto *Proto : OPT->quals()) {
6396 if (!IC->ClassImplementsProtocol(Proto, false))
6397 return false;
6398 }
6399 return true;
6400 }
6401 return false;
6402}
6403
6404/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
6405/// QT's qualified-id protocol list adopt all protocols in IDecl's list
6406/// of protocols.
6408 ObjCInterfaceDecl *IDecl) {
6409 if (!QT->isObjCQualifiedIdType())
6410 return false;
6411 const auto *OPT = QT->getAs<ObjCObjectPointerType>();
6412 if (!OPT)
6413 return false;
6414 if (!IDecl->hasDefinition())
6415 return false;
6417 CollectInheritedProtocols(IDecl, InheritedProtocols);
6418 if (InheritedProtocols.empty())
6419 return false;
6420 // Check that if every protocol in list of id<plist> conforms to a protocol
6421 // of IDecl's, then bridge casting is ok.
6422 bool Conforms = false;
6423 for (auto *Proto : OPT->quals()) {
6424 Conforms = false;
6425 for (auto *PI : InheritedProtocols) {
6426 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
6427 Conforms = true;
6428 break;
6429 }
6430 }
6431 if (!Conforms)
6432 break;
6433 }
6434 if (Conforms)
6435 return true;
6436
6437 for (auto *PI : InheritedProtocols) {
6438 // If both the right and left sides have qualifiers.
6439 bool Adopts = false;
6440 for (auto *Proto : OPT->quals()) {
6441 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
6442 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
6443 break;
6444 }
6445 if (!Adopts)
6446 return false;
6447 }
6448 return true;
6449}
6450
6451/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
6452/// the given object type.
6454 llvm::FoldingSetNodeID ID;
6455 ObjCObjectPointerType::Profile(ID, ObjectT);
6456
6457 void *InsertPos = nullptr;
6458 if (ObjCObjectPointerType *QT =
6459 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
6460 return QualType(QT, 0);
6461
6462 // Find the canonical object type.
6463 QualType Canonical;
6464 if (!ObjectT.isCanonical()) {
6465 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
6466
6467 // Regenerate InsertPos.
6468 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
6469 }
6470
6471 // No match.
6472 void *Mem =
6474 auto *QType =
6475 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
6476
6477 Types.push_back(QType);
6478 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
6479 return QualType(QType, 0);
6480}
6481
6482/// getObjCInterfaceType - Return the unique reference to the type for the
6483/// specified ObjC interface decl. The list of protocols is optional.
6485 ObjCInterfaceDecl *PrevDecl) const {
6486 if (Decl->TypeForDecl)
6487 return QualType(Decl->TypeForDecl, 0);
6488
6489 if (PrevDecl) {
6490 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
6491 Decl->TypeForDecl = PrevDecl->TypeForDecl;
6492 return QualType(PrevDecl->TypeForDecl, 0);
6493 }
6494
6495 // Prefer the definition, if there is one.
6496 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
6497 Decl = Def;
6498
6499 void *Mem = Allocate(sizeof(ObjCInterfaceType), alignof(ObjCInterfaceType));
6500 auto *T = new (Mem) ObjCInterfaceType(Decl);
6501 Decl->TypeForDecl = T;
6502 Types.push_back(T);
6503 return QualType(T, 0);
6504}
6505
6506/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
6507/// TypeOfExprType AST's (since expression's are never shared). For example,
6508/// multiple declarations that refer to "typeof(x)" all contain different
6509/// DeclRefExpr's. This doesn't effect the type checker, since it operates
6510/// on canonical type's (which are always unique).
6512 TypeOfExprType *toe;
6513 if (tofExpr->isTypeDependent()) {
6514 llvm::FoldingSetNodeID ID;
6515 DependentTypeOfExprType::Profile(ID, *this, tofExpr,
6516 Kind == TypeOfKind::Unqualified);
6517
6518 void *InsertPos = nullptr;
6520 DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
6521 if (Canon) {
6522 // We already have a "canonical" version of an identical, dependent
6523 // typeof(expr) type. Use that as our canonical type.
6524 toe = new (*this, alignof(TypeOfExprType)) TypeOfExprType(
6525 *this, tofExpr, Kind, QualType((TypeOfExprType *)Canon, 0));
6526 } else {
6527 // Build a new, canonical typeof(expr) type.
6528 Canon = new (*this, alignof(DependentTypeOfExprType))
6529 DependentTypeOfExprType(*this, tofExpr, Kind);
6530 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
6531 toe = Canon;
6532 }
6533 } else {
6534 QualType Canonical = getCanonicalType(tofExpr->getType());
6535 toe = new (*this, alignof(TypeOfExprType))
6536 TypeOfExprType(*this, tofExpr, Kind, Canonical);
6537 }
6538 Types.push_back(toe);
6539 return QualType(toe, 0);
6540}
6541
6542/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
6543/// TypeOfType nodes. The only motivation to unique these nodes would be
6544/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
6545/// an issue. This doesn't affect the type checker, since it operates
6546/// on canonical types (which are always unique).
6548 QualType Canonical = getCanonicalType(tofType);
6549 auto *tot = new (*this, alignof(TypeOfType))
6550 TypeOfType(*this, tofType, Canonical, Kind);
6551 Types.push_back(tot);
6552 return QualType(tot, 0);
6553}
6554
6555/// getReferenceQualifiedType - Given an expr, will return the type for
6556/// that expression, as in [dcl.type.simple]p4 but without taking id-expressions
6557/// and class member access into account.
6559 // C++11 [dcl.type.simple]p4:
6560 // [...]
6561 QualType T = E->getType();
6562 switch (E->getValueKind()) {
6563 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
6564 // type of e;
6565 case VK_XValue:
6566 return getRValueReferenceType(T);
6567 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
6568 // type of e;
6569 case VK_LValue:
6570 return getLValueReferenceType(T);
6571 // - otherwise, decltype(e) is the type of e.
6572 case VK_PRValue:
6573 return T;
6574 }
6575 llvm_unreachable("Unknown value kind");
6576}
6577
6578/// Unlike many "get<Type>" functions, we don't unique DecltypeType
6579/// nodes. This would never be helpful, since each such type has its own
6580/// expression, and would not give a significant memory saving, since there
6581/// is an Expr tree under each such type.
6583 // C++11 [temp.type]p2:
6584 // If an expression e involves a template parameter, decltype(e) denotes a
6585 // unique dependent type. Two such decltype-specifiers refer to the same
6586 // type only if their expressions are equivalent (14.5.6.1).
6587 QualType CanonType;
6588 if (!E->isInstantiationDependent()) {
6589 CanonType = getCanonicalType(UnderlyingType);
6590 } else if (!UnderlyingType.isNull()) {
6591 CanonType = getDecltypeType(E, QualType());
6592 } else {
6593 llvm::FoldingSetNodeID ID;
6594 DependentDecltypeType::Profile(ID, *this, E);
6595
6596 void *InsertPos = nullptr;
6597 if (DependentDecltypeType *Canon =
6598 DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos))
6599 return QualType(Canon, 0);
6600
6601 // Build a new, canonical decltype(expr) type.
6602 auto *DT =
6603 new (*this, alignof(DependentDecltypeType)) DependentDecltypeType(E);
6604 DependentDecltypeTypes.InsertNode(DT, InsertPos);
6605 Types.push_back(DT);
6606 return QualType(DT, 0);
6607 }
6608 auto *DT = new (*this, alignof(DecltypeType))
6609 DecltypeType(E, UnderlyingType, CanonType);
6610 Types.push_back(DT);
6611 return QualType(DT, 0);
6612}
6613
6615 bool FullySubstituted,
6616 ArrayRef<QualType> Expansions,
6617 UnsignedOrNone Index) const {
6618 QualType Canonical;
6619 if (FullySubstituted && Index) {
6620 Canonical = getCanonicalType(Expansions[*Index]);
6621 } else {
6622 llvm::FoldingSetNodeID ID;
6623 PackIndexingType::Profile(ID, *this, Pattern.getCanonicalType(), IndexExpr,
6624 FullySubstituted, Expansions);
6625 void *InsertPos = nullptr;
6626 PackIndexingType *Canon =
6627 DependentPackIndexingTypes.FindNodeOrInsertPos(ID, InsertPos);
6628 if (!Canon) {
6629 void *Mem = Allocate(
6630 PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
6632 Canon =
6633 new (Mem) PackIndexingType(QualType(), Pattern.getCanonicalType(),
6634 IndexExpr, FullySubstituted, Expansions);
6635 DependentPackIndexingTypes.InsertNode(Canon, InsertPos);
6636 }
6637 Canonical = QualType(Canon, 0);
6638 }
6639
6640 void *Mem =
6641 Allocate(PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
6643 auto *T = new (Mem) PackIndexingType(Canonical, Pattern, IndexExpr,
6644 FullySubstituted, Expansions);
6645 Types.push_back(T);
6646 return QualType(T, 0);
6647}
6648
6649/// getUnaryTransformationType - We don't unique these, since the memory
6650/// savings are minimal and these are rare.
6653 UnaryTransformType::UTTKind Kind) const {
6654
6655 llvm::FoldingSetNodeID ID;
6656 UnaryTransformType::Profile(ID, BaseType, UnderlyingType, Kind);
6657
6658 void *InsertPos = nullptr;
6659 if (UnaryTransformType *UT =
6660 UnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos))
6661 return QualType(UT, 0);
6662
6663 QualType CanonType;
6664 if (!BaseType->isDependentType()) {
6665 CanonType = UnderlyingType.getCanonicalType();
6666 } else {
6667 assert(UnderlyingType.isNull() || BaseType == UnderlyingType);
6668 UnderlyingType = QualType();
6669 if (QualType CanonBase = BaseType.getCanonicalType();
6670 BaseType != CanonBase) {
6671 CanonType = getUnaryTransformType(CanonBase, QualType(), Kind);
6672 assert(CanonType.isCanonical());
6673
6674 // Find the insertion position again.
6675 [[maybe_unused]] UnaryTransformType *UT =
6676 UnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
6677 assert(!UT && "broken canonicalization");
6678 }
6679 }
6680
6681 auto *UT = new (*this, alignof(UnaryTransformType))
6682 UnaryTransformType(BaseType, UnderlyingType, Kind, CanonType);
6683 UnaryTransformTypes.InsertNode(UT, InsertPos);
6684 Types.push_back(UT);
6685 return QualType(UT, 0);
6686}
6687
6688QualType ASTContext::getAutoTypeInternal(
6689 QualType DeducedType, AutoTypeKeyword Keyword, bool IsDependent,
6690 bool IsPack, TemplateDecl *TypeConstraintConcept,
6691 ArrayRef<TemplateArgument> TypeConstraintArgs, bool IsCanon) const {
6692 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto &&
6693 !TypeConstraintConcept && !IsDependent)
6694 return getAutoDeductType();
6695
6696 // Look in the folding set for an existing type.
6697 llvm::FoldingSetNodeID ID;
6698 bool IsDeducedDependent =
6699 isa_and_nonnull<TemplateTemplateParmDecl>(TypeConstraintConcept) ||
6700 (!DeducedType.isNull() && DeducedType->isDependentType());
6701 AutoType::Profile(ID, *this, DeducedType, Keyword,
6702 IsDependent || IsDeducedDependent, TypeConstraintConcept,
6703 TypeConstraintArgs);
6704 if (auto const AT_iter = AutoTypes.find(ID); AT_iter != AutoTypes.end())
6705 return QualType(AT_iter->getSecond(), 0);
6706
6707 QualType Canon;
6708 if (!IsCanon) {
6709 if (!DeducedType.isNull()) {
6710 Canon = DeducedType.getCanonicalType();
6711 } else if (TypeConstraintConcept) {
6712 bool AnyNonCanonArgs = false;
6713 auto *CanonicalConcept =
6714 cast<TemplateDecl>(TypeConstraintConcept->getCanonicalDecl());
6715 auto CanonicalConceptArgs = ::getCanonicalTemplateArguments(
6716 *this, TypeConstraintArgs, AnyNonCanonArgs);
6717 if (CanonicalConcept != TypeConstraintConcept || AnyNonCanonArgs) {
6718 Canon = getAutoTypeInternal(QualType(), Keyword, IsDependent, IsPack,
6719 CanonicalConcept, CanonicalConceptArgs,
6720 /*IsCanon=*/true);
6721 }
6722 }
6723 }
6724
6725 void *Mem = Allocate(sizeof(AutoType) +
6726 sizeof(TemplateArgument) * TypeConstraintArgs.size(),
6727 alignof(AutoType));
6728 auto *AT = new (Mem) AutoType(
6729 DeducedType, Keyword,
6730 (IsDependent ? TypeDependence::DependentInstantiation
6731 : TypeDependence::None) |
6732 (IsPack ? TypeDependence::UnexpandedPack : TypeDependence::None),
6733 Canon, TypeConstraintConcept, TypeConstraintArgs);
6734#ifndef NDEBUG
6735 llvm::FoldingSetNodeID InsertedID;
6736 AT->Profile(InsertedID, *this);
6737 assert(InsertedID == ID && "ID does not match");
6738#endif
6739 Types.push_back(AT);
6740 AutoTypes.try_emplace(ID, AT);
6741 return QualType(AT, 0);
6742}
6743
6744/// getAutoType - Return the uniqued reference to the 'auto' type which has been
6745/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
6746/// canonical deduced-but-dependent 'auto' type.
6747QualType
6749 bool IsDependent, bool IsPack,
6750 TemplateDecl *TypeConstraintConcept,
6751 ArrayRef<TemplateArgument> TypeConstraintArgs) const {
6752 assert((!IsPack || IsDependent) && "only use IsPack for a dependent pack");
6753 assert((!IsDependent || DeducedType.isNull()) &&
6754 "A dependent auto should be undeduced");
6755 return getAutoTypeInternal(DeducedType, Keyword, IsDependent, IsPack,
6756 TypeConstraintConcept, TypeConstraintArgs);
6757}
6758
6760 QualType CanonT = T.getNonPackExpansionType().getCanonicalType();
6761
6762 // Remove a type-constraint from a top-level auto or decltype(auto).
6763 if (auto *AT = CanonT->getAs<AutoType>()) {
6764 if (!AT->isConstrained())
6765 return T;
6766 return getQualifiedType(getAutoType(QualType(), AT->getKeyword(),
6767 AT->isDependentType(),
6768 AT->containsUnexpandedParameterPack()),
6769 T.getQualifiers());
6770 }
6771
6772 // FIXME: We only support constrained auto at the top level in the type of a
6773 // non-type template parameter at the moment. Once we lift that restriction,
6774 // we'll need to recursively build types containing auto here.
6775 assert(!CanonT->getContainedAutoType() ||
6776 !CanonT->getContainedAutoType()->isConstrained());
6777 return T;
6778}
6779
6780QualType ASTContext::getDeducedTemplateSpecializationTypeInternal(
6782 bool IsDependent, QualType Canon) const {
6783 // Look in the folding set for an existing type.
6784 void *InsertPos = nullptr;
6785 llvm::FoldingSetNodeID ID;
6786 DeducedTemplateSpecializationType::Profile(ID, Keyword, Template, DeducedType,
6787 IsDependent);
6788 if (DeducedTemplateSpecializationType *DTST =
6789 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
6790 return QualType(DTST, 0);
6791
6792 auto *DTST = new (*this, alignof(DeducedTemplateSpecializationType))
6793 DeducedTemplateSpecializationType(Keyword, Template, DeducedType,
6794 IsDependent, Canon);
6795
6796#ifndef NDEBUG
6797 llvm::FoldingSetNodeID TempID;
6798 DTST->Profile(TempID);
6799 assert(ID == TempID && "ID does not match");
6800#endif
6801 Types.push_back(DTST);
6802 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
6803 return QualType(DTST, 0);
6804}
6805
6806/// Return the uniqued reference to the deduced template specialization type
6807/// which has been deduced to the given type, or to the canonical undeduced
6808/// such type, or the canonical deduced-but-dependent such type.
6811 bool IsDependent) const {
6812 // FIXME: This could save an extra hash table lookup if it handled all the
6813 // parameters already being canonical.
6814 // FIXME: Can this be formed from a DependentTemplateName, such that the
6815 // keyword should be part of the canonical type?
6816 QualType Canon =
6817 DeducedType.isNull()
6818 ? getDeducedTemplateSpecializationTypeInternal(
6820 QualType(), IsDependent, QualType())
6821 : DeducedType.getCanonicalType();
6822 return getDeducedTemplateSpecializationTypeInternal(
6823 Keyword, Template, DeducedType, IsDependent, Canon);
6824}
6825
6826/// getAtomicType - Return the uniqued reference to the atomic type for
6827/// the given value type.
6829 // Unique pointers, to guarantee there is only one pointer of a particular
6830 // structure.
6831 llvm::FoldingSetNodeID ID;
6833
6834 void *InsertPos = nullptr;
6835 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
6836 return QualType(AT, 0);
6837
6838 // If the atomic value type isn't canonical, this won't be a canonical type
6839 // either, so fill in the canonical type field.
6840 QualType Canonical;
6841 if (!T.isCanonical()) {
6842 Canonical = getAtomicType(getCanonicalType(T));
6843
6844 // Get the new insert position for the node we care about.
6845 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
6846 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
6847 }
6848 auto *New = new (*this, alignof(AtomicType)) AtomicType(T, Canonical);
6849 Types.push_back(New);
6850 AtomicTypes.InsertNode(New, InsertPos);
6851 return QualType(New, 0);
6852}
6853
6854/// getAutoDeductType - Get type pattern for deducing against 'auto'.
6856 if (AutoDeductTy.isNull())
6857 AutoDeductTy = QualType(new (*this, alignof(AutoType))
6858 AutoType(QualType(), AutoTypeKeyword::Auto,
6859 TypeDependence::None, QualType(),
6860 /*concept*/ nullptr, /*args*/ {}),
6861 0);
6862 return AutoDeductTy;
6863}
6864
6865/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
6867 if (AutoRRefDeductTy.isNull())
6869 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
6870 return AutoRRefDeductTy;
6871}
6872
6873/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
6874/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
6875/// needs to agree with the definition in <stddef.h>.
6879
6881 return getFromTargetType(Target->getSizeType());
6882}
6883
6884/// Return the unique signed counterpart of the integer type
6885/// corresponding to size_t.
6889
6890/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
6891/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
6895
6896/// Return the unique unsigned counterpart of "ptrdiff_t"
6897/// integer type. The standard (C11 7.21.6.1p7) refers to this type
6898/// in the definition of %tu format specifier.
6900 return getFromTargetType(Target->getUnsignedPtrDiffType(LangAS::Default));
6901}
6902
6903/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
6905 return getFromTargetType(Target->getIntMaxType());
6906}
6907
6908/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
6910 return getFromTargetType(Target->getUIntMaxType());
6911}
6912
6913/// getSignedWCharType - Return the type of "signed wchar_t".
6914/// Used when in C++, as a GCC extension.
6916 // FIXME: derive from "Target" ?
6917 return WCharTy;
6918}
6919
6920/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
6921/// Used when in C++, as a GCC extension.
6923 // FIXME: derive from "Target" ?
6924 return UnsignedIntTy;
6925}
6926
6928 return getFromTargetType(Target->getIntPtrType());
6929}
6930
6934
6935/// Return the unique type for "pid_t" defined in
6936/// <sys/types.h>. We need this to compute the correct type for vfork().
6938 return getFromTargetType(Target->getProcessIDType());
6939}
6940
6941//===----------------------------------------------------------------------===//
6942// Type Operators
6943//===----------------------------------------------------------------------===//
6944
6946 // Push qualifiers into arrays, and then discard any remaining
6947 // qualifiers.
6948 T = getCanonicalType(T);
6950 const Type *Ty = T.getTypePtr();
6954 } else if (isa<ArrayType>(Ty)) {
6956 } else if (isa<FunctionType>(Ty)) {
6957 Result = getPointerType(QualType(Ty, 0));
6958 } else {
6959 Result = QualType(Ty, 0);
6960 }
6961
6963}
6964
6966 Qualifiers &quals) const {
6967 SplitQualType splitType = type.getSplitUnqualifiedType();
6968
6969 // FIXME: getSplitUnqualifiedType() actually walks all the way to
6970 // the unqualified desugared type and then drops it on the floor.
6971 // We then have to strip that sugar back off with
6972 // getUnqualifiedDesugaredType(), which is silly.
6973 const auto *AT =
6974 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
6975
6976 // If we don't have an array, just use the results in splitType.
6977 if (!AT) {
6978 quals = splitType.Quals;
6979 return QualType(splitType.Ty, 0);
6980 }
6981
6982 // Otherwise, recurse on the array's element type.
6983 QualType elementType = AT->getElementType();
6984 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
6985
6986 // If that didn't change the element type, AT has no qualifiers, so we
6987 // can just use the results in splitType.
6988 if (elementType == unqualElementType) {
6989 assert(quals.empty()); // from the recursive call
6990 quals = splitType.Quals;
6991 return QualType(splitType.Ty, 0);
6992 }
6993
6994 // Otherwise, add in the qualifiers from the outermost type, then
6995 // build the type back up.
6996 quals.addConsistentQualifiers(splitType.Quals);
6997
6998 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
6999 return getConstantArrayType(unqualElementType, CAT->getSize(),
7000 CAT->getSizeExpr(), CAT->getSizeModifier(), 0);
7001 }
7002
7003 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
7004 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
7005 }
7006
7007 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
7008 return getVariableArrayType(unqualElementType, VAT->getSizeExpr(),
7009 VAT->getSizeModifier(),
7010 VAT->getIndexTypeCVRQualifiers());
7011 }
7012
7013 const auto *DSAT = cast<DependentSizedArrayType>(AT);
7014 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
7015 DSAT->getSizeModifier(), 0);
7016}
7017
7018/// Attempt to unwrap two types that may both be array types with the same bound
7019/// (or both be array types of unknown bound) for the purpose of comparing the
7020/// cv-decomposition of two types per C++ [conv.qual].
7021///
7022/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
7023/// C++20 [conv.qual], if permitted by the current language mode.
7025 bool AllowPiMismatch) const {
7026 while (true) {
7027 auto *AT1 = getAsArrayType(T1);
7028 if (!AT1)
7029 return;
7030
7031 auto *AT2 = getAsArrayType(T2);
7032 if (!AT2)
7033 return;
7034
7035 // If we don't have two array types with the same constant bound nor two
7036 // incomplete array types, we've unwrapped everything we can.
7037 // C++20 also permits one type to be a constant array type and the other
7038 // to be an incomplete array type.
7039 // FIXME: Consider also unwrapping array of unknown bound and VLA.
7040 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
7041 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
7042 if (!((CAT2 && CAT1->getSize() == CAT2->getSize()) ||
7043 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
7045 return;
7046 } else if (isa<IncompleteArrayType>(AT1)) {
7047 if (!(isa<IncompleteArrayType>(AT2) ||
7048 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
7050 return;
7051 } else {
7052 return;
7053 }
7054
7055 T1 = AT1->getElementType();
7056 T2 = AT2->getElementType();
7057 }
7058}
7059
7060/// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
7061///
7062/// If T1 and T2 are both pointer types of the same kind, or both array types
7063/// with the same bound, unwraps layers from T1 and T2 until a pointer type is
7064/// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
7065///
7066/// This function will typically be called in a loop that successively
7067/// "unwraps" pointer and pointer-to-member types to compare them at each
7068/// level.
7069///
7070/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
7071/// C++20 [conv.qual], if permitted by the current language mode.
7072///
7073/// \return \c true if a pointer type was unwrapped, \c false if we reached a
7074/// pair of types that can't be unwrapped further.
7076 bool AllowPiMismatch) const {
7077 UnwrapSimilarArrayTypes(T1, T2, AllowPiMismatch);
7078
7079 const auto *T1PtrType = T1->getAs<PointerType>();
7080 const auto *T2PtrType = T2->getAs<PointerType>();
7081 if (T1PtrType && T2PtrType) {
7082 T1 = T1PtrType->getPointeeType();
7083 T2 = T2PtrType->getPointeeType();
7084 return true;
7085 }
7086
7087 if (const auto *T1MPType = T1->getAs<MemberPointerType>(),
7088 *T2MPType = T2->getAs<MemberPointerType>();
7089 T1MPType && T2MPType) {
7090 if (auto *RD1 = T1MPType->getMostRecentCXXRecordDecl(),
7091 *RD2 = T2MPType->getMostRecentCXXRecordDecl();
7092 RD1 != RD2 && RD1->getCanonicalDecl() != RD2->getCanonicalDecl())
7093 return false;
7094 if (T1MPType->getQualifier().getCanonical() !=
7095 T2MPType->getQualifier().getCanonical())
7096 return false;
7097 T1 = T1MPType->getPointeeType();
7098 T2 = T2MPType->getPointeeType();
7099 return true;
7100 }
7101
7102 if (getLangOpts().ObjC) {
7103 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
7104 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
7105 if (T1OPType && T2OPType) {
7106 T1 = T1OPType->getPointeeType();
7107 T2 = T2OPType->getPointeeType();
7108 return true;
7109 }
7110 }
7111
7112 // FIXME: Block pointers, too?
7113
7114 return false;
7115}
7116
7118 while (true) {
7119 Qualifiers Quals;
7120 T1 = getUnqualifiedArrayType(T1, Quals);
7121 T2 = getUnqualifiedArrayType(T2, Quals);
7122 if (hasSameType(T1, T2))
7123 return true;
7124 if (!UnwrapSimilarTypes(T1, T2))
7125 return false;
7126 }
7127}
7128
7130 while (true) {
7131 Qualifiers Quals1, Quals2;
7132 T1 = getUnqualifiedArrayType(T1, Quals1);
7133 T2 = getUnqualifiedArrayType(T2, Quals2);
7134
7135 Quals1.removeCVRQualifiers();
7136 Quals2.removeCVRQualifiers();
7137 if (Quals1 != Quals2)
7138 return false;
7139
7140 if (hasSameType(T1, T2))
7141 return true;
7142
7143 if (!UnwrapSimilarTypes(T1, T2, /*AllowPiMismatch*/ false))
7144 return false;
7145 }
7146}
7147
7150 SourceLocation NameLoc) const {
7151 switch (Name.getKind()) {
7154 // DNInfo work in progress: CHECKME: what about DNLoc?
7156 NameLoc);
7157
7160 // DNInfo work in progress: CHECKME: what about DNLoc?
7161 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
7162 }
7163
7166 return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
7167 }
7168
7172 DeclarationName DName;
7173 if (const IdentifierInfo *II = TN.getIdentifier()) {
7174 DName = DeclarationNames.getIdentifier(II);
7175 return DeclarationNameInfo(DName, NameLoc);
7176 } else {
7177 DName = DeclarationNames.getCXXOperatorName(TN.getOperator());
7178 // DNInfo work in progress: FIXME: source locations?
7179 DeclarationNameLoc DNLoc =
7181 return DeclarationNameInfo(DName, NameLoc, DNLoc);
7182 }
7183 }
7184
7188 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
7189 NameLoc);
7190 }
7191
7196 NameLoc);
7197 }
7200 NameLoc);
7203 return getNameForTemplate(DTS->getUnderlying(), NameLoc);
7204 }
7205 }
7206
7207 llvm_unreachable("bad template name kind!");
7208}
7209
7210static const TemplateArgument *
7212 auto handleParam = [](auto *TP) -> const TemplateArgument * {
7213 if (!TP->hasDefaultArgument())
7214 return nullptr;
7215 return &TP->getDefaultArgument().getArgument();
7216 };
7217 switch (P->getKind()) {
7218 case NamedDecl::TemplateTypeParm:
7219 return handleParam(cast<TemplateTypeParmDecl>(P));
7220 case NamedDecl::NonTypeTemplateParm:
7221 return handleParam(cast<NonTypeTemplateParmDecl>(P));
7222 case NamedDecl::TemplateTemplateParm:
7223 return handleParam(cast<TemplateTemplateParmDecl>(P));
7224 default:
7225 llvm_unreachable("Unexpected template parameter kind");
7226 }
7227}
7228
7230 bool IgnoreDeduced) const {
7231 while (std::optional<TemplateName> UnderlyingOrNone =
7232 Name.desugar(IgnoreDeduced))
7233 Name = *UnderlyingOrNone;
7234
7235 switch (Name.getKind()) {
7238 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template))
7240
7241 // The canonical template name is the canonical template declaration.
7242 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
7243 }
7244
7247 llvm_unreachable("cannot canonicalize unresolved template");
7248
7251 assert(DTN && "Non-dependent template names must refer to template decls.");
7252 NestedNameSpecifier Qualifier = DTN->getQualifier();
7253 NestedNameSpecifier CanonQualifier = Qualifier.getCanonical();
7254 if (Qualifier != CanonQualifier || !DTN->hasTemplateKeyword())
7255 return getDependentTemplateName({CanonQualifier, DTN->getName(),
7256 /*HasTemplateKeyword=*/true});
7257 return Name;
7258 }
7259
7263 TemplateArgument canonArgPack =
7266 canonArgPack, subst->getAssociatedDecl()->getCanonicalDecl(),
7267 subst->getIndex(), subst->getFinal());
7268 }
7270 assert(IgnoreDeduced == false);
7272 DefaultArguments DefArgs = DTS->getDefaultArguments();
7273 TemplateName Underlying = DTS->getUnderlying();
7274
7275 TemplateName CanonUnderlying =
7276 getCanonicalTemplateName(Underlying, /*IgnoreDeduced=*/true);
7277 bool NonCanonical = CanonUnderlying != Underlying;
7278 auto CanonArgs =
7279 getCanonicalTemplateArguments(*this, DefArgs.Args, NonCanonical);
7280
7281 ArrayRef<NamedDecl *> Params =
7282 CanonUnderlying.getAsTemplateDecl()->getTemplateParameters()->asArray();
7283 assert(CanonArgs.size() <= Params.size());
7284 // A deduced template name which deduces the same default arguments already
7285 // declared in the underlying template is the same template as the
7286 // underlying template. We need need to note any arguments which differ from
7287 // the corresponding declaration. If any argument differs, we must build a
7288 // deduced template name.
7289 for (int I = CanonArgs.size() - 1; I >= 0; --I) {
7291 if (!A)
7292 break;
7293 auto CanonParamDefArg = getCanonicalTemplateArgument(*A);
7294 TemplateArgument &CanonDefArg = CanonArgs[I];
7295 if (CanonDefArg.structurallyEquals(CanonParamDefArg))
7296 continue;
7297 // Keep popping from the back any deault arguments which are the same.
7298 if (I == int(CanonArgs.size() - 1))
7299 CanonArgs.pop_back();
7300 NonCanonical = true;
7301 }
7302 return NonCanonical ? getDeducedTemplateName(
7303 CanonUnderlying,
7304 /*DefaultArgs=*/{DefArgs.StartPos, CanonArgs})
7305 : Name;
7306 }
7310 llvm_unreachable("always sugar node");
7311 }
7312
7313 llvm_unreachable("bad template name!");
7314}
7315
7317 const TemplateName &Y,
7318 bool IgnoreDeduced) const {
7319 return getCanonicalTemplateName(X, IgnoreDeduced) ==
7320 getCanonicalTemplateName(Y, IgnoreDeduced);
7321}
7322
7324 const AssociatedConstraint &ACX, const AssociatedConstraint &ACY) const {
7325 if (ACX.ArgPackSubstIndex != ACY.ArgPackSubstIndex)
7326 return false;
7328 return false;
7329 return true;
7330}
7331
7332bool ASTContext::isSameConstraintExpr(const Expr *XCE, const Expr *YCE) const {
7333 if (!XCE != !YCE)
7334 return false;
7335
7336 if (!XCE)
7337 return true;
7338
7339 llvm::FoldingSetNodeID XCEID, YCEID;
7340 XCE->Profile(XCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7341 YCE->Profile(YCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7342 return XCEID == YCEID;
7343}
7344
7346 const TypeConstraint *YTC) const {
7347 if (!XTC != !YTC)
7348 return false;
7349
7350 if (!XTC)
7351 return true;
7352
7353 auto *NCX = XTC->getNamedConcept();
7354 auto *NCY = YTC->getNamedConcept();
7355 if (!NCX || !NCY || !isSameEntity(NCX, NCY))
7356 return false;
7359 return false;
7361 if (XTC->getConceptReference()
7363 ->NumTemplateArgs !=
7365 return false;
7366
7367 // Compare slowly by profiling.
7368 //
7369 // We couldn't compare the profiling result for the template
7370 // args here. Consider the following example in different modules:
7371 //
7372 // template <__integer_like _Tp, C<_Tp> Sentinel>
7373 // constexpr _Tp operator()(_Tp &&__t, Sentinel &&last) const {
7374 // return __t;
7375 // }
7376 //
7377 // When we compare the profiling result for `C<_Tp>` in different
7378 // modules, it will compare the type of `_Tp` in different modules.
7379 // However, the type of `_Tp` in different modules refer to different
7380 // types here naturally. So we couldn't compare the profiling result
7381 // for the template args directly.
7384}
7385
7387 const NamedDecl *Y) const {
7388 if (X->getKind() != Y->getKind())
7389 return false;
7390
7391 if (auto *TX = dyn_cast<TemplateTypeParmDecl>(X)) {
7392 auto *TY = cast<TemplateTypeParmDecl>(Y);
7393 if (TX->isParameterPack() != TY->isParameterPack())
7394 return false;
7395 if (TX->hasTypeConstraint() != TY->hasTypeConstraint())
7396 return false;
7397 return isSameTypeConstraint(TX->getTypeConstraint(),
7398 TY->getTypeConstraint());
7399 }
7400
7401 if (auto *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
7402 auto *TY = cast<NonTypeTemplateParmDecl>(Y);
7403 return TX->isParameterPack() == TY->isParameterPack() &&
7404 TX->getASTContext().hasSameType(TX->getType(), TY->getType()) &&
7405 isSameConstraintExpr(TX->getPlaceholderTypeConstraint(),
7406 TY->getPlaceholderTypeConstraint());
7407 }
7408
7410 auto *TY = cast<TemplateTemplateParmDecl>(Y);
7411 return TX->isParameterPack() == TY->isParameterPack() &&
7412 isSameTemplateParameterList(TX->getTemplateParameters(),
7413 TY->getTemplateParameters());
7414}
7415
7417 const TemplateParameterList *X, const TemplateParameterList *Y) const {
7418 if (X->size() != Y->size())
7419 return false;
7420
7421 for (unsigned I = 0, N = X->size(); I != N; ++I)
7422 if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I)))
7423 return false;
7424
7425 return isSameConstraintExpr(X->getRequiresClause(), Y->getRequiresClause());
7426}
7427
7429 const NamedDecl *Y) const {
7430 // If the type parameter isn't the same already, we don't need to check the
7431 // default argument further.
7432 if (!isSameTemplateParameter(X, Y))
7433 return false;
7434
7435 if (auto *TTPX = dyn_cast<TemplateTypeParmDecl>(X)) {
7436 auto *TTPY = cast<TemplateTypeParmDecl>(Y);
7437 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7438 return false;
7439
7440 return hasSameType(TTPX->getDefaultArgument().getArgument().getAsType(),
7441 TTPY->getDefaultArgument().getArgument().getAsType());
7442 }
7443
7444 if (auto *NTTPX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
7445 auto *NTTPY = cast<NonTypeTemplateParmDecl>(Y);
7446 if (!NTTPX->hasDefaultArgument() || !NTTPY->hasDefaultArgument())
7447 return false;
7448
7449 Expr *DefaultArgumentX =
7450 NTTPX->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7451 Expr *DefaultArgumentY =
7452 NTTPY->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7453 llvm::FoldingSetNodeID XID, YID;
7454 DefaultArgumentX->Profile(XID, *this, /*Canonical=*/true);
7455 DefaultArgumentY->Profile(YID, *this, /*Canonical=*/true);
7456 return XID == YID;
7457 }
7458
7459 auto *TTPX = cast<TemplateTemplateParmDecl>(X);
7460 auto *TTPY = cast<TemplateTemplateParmDecl>(Y);
7461
7462 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7463 return false;
7464
7465 const TemplateArgument &TAX = TTPX->getDefaultArgument().getArgument();
7466 const TemplateArgument &TAY = TTPY->getDefaultArgument().getArgument();
7467 return hasSameTemplateName(TAX.getAsTemplate(), TAY.getAsTemplate());
7468}
7469
7471 const NestedNameSpecifier Y) {
7472 if (X == Y)
7473 return true;
7474 if (!X || !Y)
7475 return false;
7476
7477 auto Kind = X.getKind();
7478 if (Kind != Y.getKind())
7479 return false;
7480
7481 // FIXME: For namespaces and types, we're permitted to check that the entity
7482 // is named via the same tokens. We should probably do so.
7483 switch (Kind) {
7485 auto [NamespaceX, PrefixX] = X.getAsNamespaceAndPrefix();
7486 auto [NamespaceY, PrefixY] = Y.getAsNamespaceAndPrefix();
7487 if (!declaresSameEntity(NamespaceX->getNamespace(),
7488 NamespaceY->getNamespace()))
7489 return false;
7490 return isSameQualifier(PrefixX, PrefixY);
7491 }
7493 const auto *TX = X.getAsType(), *TY = Y.getAsType();
7494 if (TX->getCanonicalTypeInternal() != TY->getCanonicalTypeInternal())
7495 return false;
7496 return isSameQualifier(TX->getPrefix(), TY->getPrefix());
7497 }
7501 return true;
7502 }
7503 llvm_unreachable("unhandled qualifier kind");
7504}
7505
7506static bool hasSameCudaAttrs(const FunctionDecl *A, const FunctionDecl *B) {
7507 if (!A->getASTContext().getLangOpts().CUDA)
7508 return true; // Target attributes are overloadable in CUDA compilation only.
7509 if (A->hasAttr<CUDADeviceAttr>() != B->hasAttr<CUDADeviceAttr>())
7510 return false;
7511 if (A->hasAttr<CUDADeviceAttr>() && B->hasAttr<CUDADeviceAttr>())
7512 return A->hasAttr<CUDAHostAttr>() == B->hasAttr<CUDAHostAttr>();
7513 return true; // unattributed and __host__ functions are the same.
7514}
7515
7516/// Determine whether the attributes we can overload on are identical for A and
7517/// B. Will ignore any overloadable attrs represented in the type of A and B.
7519 const FunctionDecl *B) {
7520 // Note that pass_object_size attributes are represented in the function's
7521 // ExtParameterInfo, so we don't need to check them here.
7522
7523 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
7524 auto AEnableIfAttrs = A->specific_attrs<EnableIfAttr>();
7525 auto BEnableIfAttrs = B->specific_attrs<EnableIfAttr>();
7526
7527 for (auto Pair : zip_longest(AEnableIfAttrs, BEnableIfAttrs)) {
7528 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
7529 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
7530
7531 // Return false if the number of enable_if attributes is different.
7532 if (!Cand1A || !Cand2A)
7533 return false;
7534
7535 Cand1ID.clear();
7536 Cand2ID.clear();
7537
7538 (*Cand1A)->getCond()->Profile(Cand1ID, A->getASTContext(), true);
7539 (*Cand2A)->getCond()->Profile(Cand2ID, B->getASTContext(), true);
7540
7541 // Return false if any of the enable_if expressions of A and B are
7542 // different.
7543 if (Cand1ID != Cand2ID)
7544 return false;
7545 }
7546 return hasSameCudaAttrs(A, B);
7547}
7548
7549bool ASTContext::isSameEntity(const NamedDecl *X, const NamedDecl *Y) const {
7550 // Caution: this function is called by the AST reader during deserialization,
7551 // so it cannot rely on AST invariants being met. Non-trivial accessors
7552 // should be avoided, along with any traversal of redeclaration chains.
7553
7554 if (X == Y)
7555 return true;
7556
7557 if (X->getDeclName() != Y->getDeclName())
7558 return false;
7559
7560 // Must be in the same context.
7561 //
7562 // Note that we can't use DeclContext::Equals here, because the DeclContexts
7563 // could be two different declarations of the same function. (We will fix the
7564 // semantic DC to refer to the primary definition after merging.)
7565 if (!declaresSameEntity(cast<Decl>(X->getDeclContext()->getRedeclContext()),
7567 return false;
7568
7569 // If either X or Y are local to the owning module, they are only possible to
7570 // be the same entity if they are in the same module.
7571 if (X->isModuleLocal() || Y->isModuleLocal())
7572 if (!isInSameModule(X->getOwningModule(), Y->getOwningModule()))
7573 return false;
7574
7575 // Two typedefs refer to the same entity if they have the same underlying
7576 // type.
7577 if (const auto *TypedefX = dyn_cast<TypedefNameDecl>(X))
7578 if (const auto *TypedefY = dyn_cast<TypedefNameDecl>(Y))
7579 return hasSameType(TypedefX->getUnderlyingType(),
7580 TypedefY->getUnderlyingType());
7581
7582 // Must have the same kind.
7583 if (X->getKind() != Y->getKind())
7584 return false;
7585
7586 // Objective-C classes and protocols with the same name always match.
7588 return true;
7589
7591 // No need to handle these here: we merge them when adding them to the
7592 // template.
7593 return false;
7594 }
7595
7596 // Compatible tags match.
7597 if (const auto *TagX = dyn_cast<TagDecl>(X)) {
7598 const auto *TagY = cast<TagDecl>(Y);
7599 return (TagX->getTagKind() == TagY->getTagKind()) ||
7600 ((TagX->getTagKind() == TagTypeKind::Struct ||
7601 TagX->getTagKind() == TagTypeKind::Class ||
7602 TagX->getTagKind() == TagTypeKind::Interface) &&
7603 (TagY->getTagKind() == TagTypeKind::Struct ||
7604 TagY->getTagKind() == TagTypeKind::Class ||
7605 TagY->getTagKind() == TagTypeKind::Interface));
7606 }
7607
7608 // Functions with the same type and linkage match.
7609 // FIXME: This needs to cope with merging of prototyped/non-prototyped
7610 // functions, etc.
7611 if (const auto *FuncX = dyn_cast<FunctionDecl>(X)) {
7612 const auto *FuncY = cast<FunctionDecl>(Y);
7613 if (const auto *CtorX = dyn_cast<CXXConstructorDecl>(X)) {
7614 const auto *CtorY = cast<CXXConstructorDecl>(Y);
7615 if (CtorX->getInheritedConstructor() &&
7616 !isSameEntity(CtorX->getInheritedConstructor().getConstructor(),
7617 CtorY->getInheritedConstructor().getConstructor()))
7618 return false;
7619 }
7620
7621 if (FuncX->isMultiVersion() != FuncY->isMultiVersion())
7622 return false;
7623
7624 // Multiversioned functions with different feature strings are represented
7625 // as separate declarations.
7626 if (FuncX->isMultiVersion()) {
7627 const auto *TAX = FuncX->getAttr<TargetAttr>();
7628 const auto *TAY = FuncY->getAttr<TargetAttr>();
7629 assert(TAX && TAY && "Multiversion Function without target attribute");
7630
7631 if (TAX->getFeaturesStr() != TAY->getFeaturesStr())
7632 return false;
7633 }
7634
7635 // Per C++20 [temp.over.link]/4, friends in different classes are sometimes
7636 // not the same entity if they are constrained.
7637 if ((FuncX->isMemberLikeConstrainedFriend() ||
7638 FuncY->isMemberLikeConstrainedFriend()) &&
7639 !FuncX->getLexicalDeclContext()->Equals(
7640 FuncY->getLexicalDeclContext())) {
7641 return false;
7642 }
7643
7644 if (!isSameAssociatedConstraint(FuncX->getTrailingRequiresClause(),
7645 FuncY->getTrailingRequiresClause()))
7646 return false;
7647
7648 auto GetTypeAsWritten = [](const FunctionDecl *FD) {
7649 // Map to the first declaration that we've already merged into this one.
7650 // The TSI of redeclarations might not match (due to calling conventions
7651 // being inherited onto the type but not the TSI), but the TSI type of
7652 // the first declaration of the function should match across modules.
7653 FD = FD->getCanonicalDecl();
7654 return FD->getTypeSourceInfo() ? FD->getTypeSourceInfo()->getType()
7655 : FD->getType();
7656 };
7657 QualType XT = GetTypeAsWritten(FuncX), YT = GetTypeAsWritten(FuncY);
7658 if (!hasSameType(XT, YT)) {
7659 // We can get functions with different types on the redecl chain in C++17
7660 // if they have differing exception specifications and at least one of
7661 // the excpetion specs is unresolved.
7662 auto *XFPT = XT->getAs<FunctionProtoType>();
7663 auto *YFPT = YT->getAs<FunctionProtoType>();
7664 if (getLangOpts().CPlusPlus17 && XFPT && YFPT &&
7665 (isUnresolvedExceptionSpec(XFPT->getExceptionSpecType()) ||
7668 return true;
7669 return false;
7670 }
7671
7672 return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() &&
7673 hasSameOverloadableAttrs(FuncX, FuncY);
7674 }
7675
7676 // Variables with the same type and linkage match.
7677 if (const auto *VarX = dyn_cast<VarDecl>(X)) {
7678 const auto *VarY = cast<VarDecl>(Y);
7679 if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) {
7680 // During deserialization, we might compare variables before we load
7681 // their types. Assume the types will end up being the same.
7682 if (VarX->getType().isNull() || VarY->getType().isNull())
7683 return true;
7684
7685 if (hasSameType(VarX->getType(), VarY->getType()))
7686 return true;
7687
7688 // We can get decls with different types on the redecl chain. Eg.
7689 // template <typename T> struct S { static T Var[]; }; // #1
7690 // template <typename T> T S<T>::Var[sizeof(T)]; // #2
7691 // Only? happens when completing an incomplete array type. In this case
7692 // when comparing #1 and #2 we should go through their element type.
7693 const ArrayType *VarXTy = getAsArrayType(VarX->getType());
7694 const ArrayType *VarYTy = getAsArrayType(VarY->getType());
7695 if (!VarXTy || !VarYTy)
7696 return false;
7697 if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType())
7698 return hasSameType(VarXTy->getElementType(), VarYTy->getElementType());
7699 }
7700 return false;
7701 }
7702
7703 // Namespaces with the same name and inlinedness match.
7704 if (const auto *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
7705 const auto *NamespaceY = cast<NamespaceDecl>(Y);
7706 return NamespaceX->isInline() == NamespaceY->isInline();
7707 }
7708
7709 // Identical template names and kinds match if their template parameter lists
7710 // and patterns match.
7711 if (const auto *TemplateX = dyn_cast<TemplateDecl>(X)) {
7712 const auto *TemplateY = cast<TemplateDecl>(Y);
7713
7714 // ConceptDecl wouldn't be the same if their constraint expression differs.
7715 if (const auto *ConceptX = dyn_cast<ConceptDecl>(X)) {
7716 const auto *ConceptY = cast<ConceptDecl>(Y);
7717 if (!isSameConstraintExpr(ConceptX->getConstraintExpr(),
7718 ConceptY->getConstraintExpr()))
7719 return false;
7720 }
7721
7722 return isSameEntity(TemplateX->getTemplatedDecl(),
7723 TemplateY->getTemplatedDecl()) &&
7724 isSameTemplateParameterList(TemplateX->getTemplateParameters(),
7725 TemplateY->getTemplateParameters());
7726 }
7727
7728 // Fields with the same name and the same type match.
7729 if (const auto *FDX = dyn_cast<FieldDecl>(X)) {
7730 const auto *FDY = cast<FieldDecl>(Y);
7731 // FIXME: Also check the bitwidth is odr-equivalent, if any.
7732 return hasSameType(FDX->getType(), FDY->getType());
7733 }
7734
7735 // Indirect fields with the same target field match.
7736 if (const auto *IFDX = dyn_cast<IndirectFieldDecl>(X)) {
7737 const auto *IFDY = cast<IndirectFieldDecl>(Y);
7738 return IFDX->getAnonField()->getCanonicalDecl() ==
7739 IFDY->getAnonField()->getCanonicalDecl();
7740 }
7741
7742 // Enumerators with the same name match.
7744 // FIXME: Also check the value is odr-equivalent.
7745 return true;
7746
7747 // Using shadow declarations with the same target match.
7748 if (const auto *USX = dyn_cast<UsingShadowDecl>(X)) {
7749 const auto *USY = cast<UsingShadowDecl>(Y);
7750 return declaresSameEntity(USX->getTargetDecl(), USY->getTargetDecl());
7751 }
7752
7753 // Using declarations with the same qualifier match. (We already know that
7754 // the name matches.)
7755 if (const auto *UX = dyn_cast<UsingDecl>(X)) {
7756 const auto *UY = cast<UsingDecl>(Y);
7757 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7758 UX->hasTypename() == UY->hasTypename() &&
7759 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7760 }
7761 if (const auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) {
7762 const auto *UY = cast<UnresolvedUsingValueDecl>(Y);
7763 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7764 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7765 }
7766 if (const auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X)) {
7767 return isSameQualifier(
7768 UX->getQualifier(),
7769 cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier());
7770 }
7771
7772 // Using-pack declarations are only created by instantiation, and match if
7773 // they're instantiated from matching UnresolvedUsing...Decls.
7774 if (const auto *UX = dyn_cast<UsingPackDecl>(X)) {
7775 return declaresSameEntity(
7776 UX->getInstantiatedFromUsingDecl(),
7777 cast<UsingPackDecl>(Y)->getInstantiatedFromUsingDecl());
7778 }
7779
7780 // Namespace alias definitions with the same target match.
7781 if (const auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) {
7782 const auto *NAY = cast<NamespaceAliasDecl>(Y);
7783 return NAX->getNamespace()->Equals(NAY->getNamespace());
7784 }
7785
7786 return false;
7787}
7788
7791 switch (Arg.getKind()) {
7793 return Arg;
7794
7796 return TemplateArgument(Arg.getAsExpr(), /*IsCanonical=*/true,
7797 Arg.getIsDefaulted());
7798
7800 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
7802 Arg.getIsDefaulted());
7803 }
7804
7807 /*isNullPtr*/ true, Arg.getIsDefaulted());
7808
7811 Arg.getIsDefaulted());
7812
7814 return TemplateArgument(
7817
7820
7822 return TemplateArgument(*this,
7825
7828 /*isNullPtr*/ false, Arg.getIsDefaulted());
7829
7831 bool AnyNonCanonArgs = false;
7832 auto CanonArgs = ::getCanonicalTemplateArguments(
7833 *this, Arg.pack_elements(), AnyNonCanonArgs);
7834 if (!AnyNonCanonArgs)
7835 return Arg;
7837 const_cast<ASTContext &>(*this), CanonArgs);
7838 NewArg.setIsDefaulted(Arg.getIsDefaulted());
7839 return NewArg;
7840 }
7841 }
7842
7843 // Silence GCC warning
7844 llvm_unreachable("Unhandled template argument kind");
7845}
7846
7848 const TemplateArgument &Arg2) const {
7849 if (Arg1.getKind() != Arg2.getKind())
7850 return false;
7851
7852 switch (Arg1.getKind()) {
7854 llvm_unreachable("Comparing NULL template argument");
7855
7857 return hasSameType(Arg1.getAsType(), Arg2.getAsType());
7858
7860 return Arg1.getAsDecl()->getUnderlyingDecl()->getCanonicalDecl() ==
7862
7864 return hasSameType(Arg1.getNullPtrType(), Arg2.getNullPtrType());
7865
7870
7872 return llvm::APSInt::isSameValue(Arg1.getAsIntegral(),
7873 Arg2.getAsIntegral());
7874
7876 return Arg1.structurallyEquals(Arg2);
7877
7879 llvm::FoldingSetNodeID ID1, ID2;
7880 Arg1.getAsExpr()->Profile(ID1, *this, /*Canonical=*/true);
7881 Arg2.getAsExpr()->Profile(ID2, *this, /*Canonical=*/true);
7882 return ID1 == ID2;
7883 }
7884
7886 return llvm::equal(
7887 Arg1.getPackAsArray(), Arg2.getPackAsArray(),
7888 [&](const TemplateArgument &Arg1, const TemplateArgument &Arg2) {
7889 return isSameTemplateArgument(Arg1, Arg2);
7890 });
7891 }
7892
7893 llvm_unreachable("Unhandled template argument kind");
7894}
7895
7897 // Handle the non-qualified case efficiently.
7898 if (!T.hasLocalQualifiers()) {
7899 // Handle the common positive case fast.
7900 if (const auto *AT = dyn_cast<ArrayType>(T))
7901 return AT;
7902 }
7903
7904 // Handle the common negative case fast.
7905 if (!isa<ArrayType>(T.getCanonicalType()))
7906 return nullptr;
7907
7908 // Apply any qualifiers from the array type to the element type. This
7909 // implements C99 6.7.3p8: "If the specification of an array type includes
7910 // any type qualifiers, the element type is so qualified, not the array type."
7911
7912 // If we get here, we either have type qualifiers on the type, or we have
7913 // sugar such as a typedef in the way. If we have type qualifiers on the type
7914 // we must propagate them down into the element type.
7915
7916 SplitQualType split = T.getSplitDesugaredType();
7917 Qualifiers qs = split.Quals;
7918
7919 // If we have a simple case, just return now.
7920 const auto *ATy = dyn_cast<ArrayType>(split.Ty);
7921 if (!ATy || qs.empty())
7922 return ATy;
7923
7924 // Otherwise, we have an array and we have qualifiers on it. Push the
7925 // qualifiers into the array element type and return a new array type.
7926 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
7927
7928 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
7929 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
7930 CAT->getSizeExpr(),
7931 CAT->getSizeModifier(),
7932 CAT->getIndexTypeCVRQualifiers()));
7933 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
7935 IAT->getSizeModifier(),
7936 IAT->getIndexTypeCVRQualifiers()));
7937
7938 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
7940 NewEltTy, DSAT->getSizeExpr(), DSAT->getSizeModifier(),
7941 DSAT->getIndexTypeCVRQualifiers()));
7942
7943 const auto *VAT = cast<VariableArrayType>(ATy);
7944 return cast<ArrayType>(
7945 getVariableArrayType(NewEltTy, VAT->getSizeExpr(), VAT->getSizeModifier(),
7946 VAT->getIndexTypeCVRQualifiers()));
7947}
7948
7950 if (getLangOpts().HLSL && T->isConstantArrayType())
7951 return getArrayParameterType(T);
7952 if (T->isArrayType() || T->isFunctionType())
7953 return getDecayedType(T);
7954 return T;
7955}
7956
7960 return T.getUnqualifiedType();
7961}
7962
7964 // C++ [except.throw]p3:
7965 // A throw-expression initializes a temporary object, called the exception
7966 // object, the type of which is determined by removing any top-level
7967 // cv-qualifiers from the static type of the operand of throw and adjusting
7968 // the type from "array of T" or "function returning T" to "pointer to T"
7969 // or "pointer to function returning T", [...]
7971 if (T->isArrayType() || T->isFunctionType())
7972 T = getDecayedType(T);
7973 return T.getUnqualifiedType();
7974}
7975
7976/// getArrayDecayedType - Return the properly qualified result of decaying the
7977/// specified array type to a pointer. This operation is non-trivial when
7978/// handling typedefs etc. The canonical type of "T" must be an array type,
7979/// this returns a pointer to a properly qualified element of the array.
7980///
7981/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
7983 // Get the element type with 'getAsArrayType' so that we don't lose any
7984 // typedefs in the element type of the array. This also handles propagation
7985 // of type qualifiers from the array type into the element type if present
7986 // (C99 6.7.3p8).
7987 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
7988 assert(PrettyArrayType && "Not an array type!");
7989
7990 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
7991
7992 // int x[restrict 4] -> int *restrict
7994 PrettyArrayType->getIndexTypeQualifiers());
7995
7996 // int x[_Nullable] -> int * _Nullable
7997 if (auto Nullability = Ty->getNullability()) {
7998 Result = const_cast<ASTContext *>(this)->getAttributedType(*Nullability,
7999 Result, Result);
8000 }
8001 return Result;
8002}
8003
8005 return getBaseElementType(array->getElementType());
8006}
8007
8009 Qualifiers qs;
8010 while (true) {
8011 SplitQualType split = type.getSplitDesugaredType();
8012 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
8013 if (!array) break;
8014
8015 type = array->getElementType();
8017 }
8018
8019 return getQualifiedType(type, qs);
8020}
8021
8022/// getConstantArrayElementCount - Returns number of constant array elements.
8023uint64_t
8025 uint64_t ElementCount = 1;
8026 do {
8027 ElementCount *= CA->getZExtSize();
8028 CA = dyn_cast_or_null<ConstantArrayType>(
8030 } while (CA);
8031 return ElementCount;
8032}
8033
8035 const ArrayInitLoopExpr *AILE) const {
8036 if (!AILE)
8037 return 0;
8038
8039 uint64_t ElementCount = 1;
8040
8041 do {
8042 ElementCount *= AILE->getArraySize().getZExtValue();
8043 AILE = dyn_cast<ArrayInitLoopExpr>(AILE->getSubExpr());
8044 } while (AILE);
8045
8046 return ElementCount;
8047}
8048
8049/// getFloatingRank - Return a relative rank for floating point types.
8050/// This routine will assert if passed a built-in type that isn't a float.
8052 if (const auto *CT = T->getAs<ComplexType>())
8053 return getFloatingRank(CT->getElementType());
8054
8055 switch (T->castAs<BuiltinType>()->getKind()) {
8056 default: llvm_unreachable("getFloatingRank(): not a floating type");
8057 case BuiltinType::Float16: return Float16Rank;
8058 case BuiltinType::Half: return HalfRank;
8059 case BuiltinType::Float: return FloatRank;
8060 case BuiltinType::Double: return DoubleRank;
8061 case BuiltinType::LongDouble: return LongDoubleRank;
8062 case BuiltinType::Float128: return Float128Rank;
8063 case BuiltinType::BFloat16: return BFloat16Rank;
8064 case BuiltinType::Ibm128: return Ibm128Rank;
8065 }
8066}
8067
8068/// getFloatingTypeOrder - Compare the rank of the two specified floating
8069/// point types, ignoring the domain of the type (i.e. 'double' ==
8070/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
8071/// LHS < RHS, return -1.
8073 FloatingRank LHSR = getFloatingRank(LHS);
8074 FloatingRank RHSR = getFloatingRank(RHS);
8075
8076 if (LHSR == RHSR)
8077 return 0;
8078 if (LHSR > RHSR)
8079 return 1;
8080 return -1;
8081}
8082
8085 return 0;
8086 return getFloatingTypeOrder(LHS, RHS);
8087}
8088
8089/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
8090/// routine will assert if passed a built-in type that isn't an integer or enum,
8091/// or if it is not canonicalized.
8092unsigned ASTContext::getIntegerRank(const Type *T) const {
8093 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
8094
8095 // Results in this 'losing' to any type of the same size, but winning if
8096 // larger.
8097 if (const auto *EIT = dyn_cast<BitIntType>(T))
8098 return 0 + (EIT->getNumBits() << 3);
8099
8100 switch (cast<BuiltinType>(T)->getKind()) {
8101 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
8102 case BuiltinType::Bool:
8103 return 1 + (getIntWidth(BoolTy) << 3);
8104 case BuiltinType::Char_S:
8105 case BuiltinType::Char_U:
8106 case BuiltinType::SChar:
8107 case BuiltinType::UChar:
8108 return 2 + (getIntWidth(CharTy) << 3);
8109 case BuiltinType::Short:
8110 case BuiltinType::UShort:
8111 return 3 + (getIntWidth(ShortTy) << 3);
8112 case BuiltinType::Int:
8113 case BuiltinType::UInt:
8114 return 4 + (getIntWidth(IntTy) << 3);
8115 case BuiltinType::Long:
8116 case BuiltinType::ULong:
8117 return 5 + (getIntWidth(LongTy) << 3);
8118 case BuiltinType::LongLong:
8119 case BuiltinType::ULongLong:
8120 return 6 + (getIntWidth(LongLongTy) << 3);
8121 case BuiltinType::Int128:
8122 case BuiltinType::UInt128:
8123 return 7 + (getIntWidth(Int128Ty) << 3);
8124
8125 // "The ranks of char8_t, char16_t, char32_t, and wchar_t equal the ranks of
8126 // their underlying types" [c++20 conv.rank]
8127 case BuiltinType::Char8:
8128 return getIntegerRank(UnsignedCharTy.getTypePtr());
8129 case BuiltinType::Char16:
8130 return getIntegerRank(
8131 getFromTargetType(Target->getChar16Type()).getTypePtr());
8132 case BuiltinType::Char32:
8133 return getIntegerRank(
8134 getFromTargetType(Target->getChar32Type()).getTypePtr());
8135 case BuiltinType::WChar_S:
8136 case BuiltinType::WChar_U:
8137 return getIntegerRank(
8138 getFromTargetType(Target->getWCharType()).getTypePtr());
8139 }
8140}
8141
8142/// Whether this is a promotable bitfield reference according
8143/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
8144///
8145/// \returns the type this bit-field will promote to, or NULL if no
8146/// promotion occurs.
8148 if (E->isTypeDependent() || E->isValueDependent())
8149 return {};
8150
8151 // C++ [conv.prom]p5:
8152 // If the bit-field has an enumerated type, it is treated as any other
8153 // value of that type for promotion purposes.
8155 return {};
8156
8157 // FIXME: We should not do this unless E->refersToBitField() is true. This
8158 // matters in C where getSourceBitField() will find bit-fields for various
8159 // cases where the source expression is not a bit-field designator.
8160
8161 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
8162 if (!Field)
8163 return {};
8164
8165 QualType FT = Field->getType();
8166
8167 uint64_t BitWidth = Field->getBitWidthValue();
8168 uint64_t IntSize = getTypeSize(IntTy);
8169 // C++ [conv.prom]p5:
8170 // A prvalue for an integral bit-field can be converted to a prvalue of type
8171 // int if int can represent all the values of the bit-field; otherwise, it
8172 // can be converted to unsigned int if unsigned int can represent all the
8173 // values of the bit-field. If the bit-field is larger yet, no integral
8174 // promotion applies to it.
8175 // C11 6.3.1.1/2:
8176 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
8177 // If an int can represent all values of the original type (as restricted by
8178 // the width, for a bit-field), the value is converted to an int; otherwise,
8179 // it is converted to an unsigned int.
8180 //
8181 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
8182 // We perform that promotion here to match GCC and C++.
8183 // FIXME: C does not permit promotion of an enum bit-field whose rank is
8184 // greater than that of 'int'. We perform that promotion to match GCC.
8185 //
8186 // C23 6.3.1.1p2:
8187 // The value from a bit-field of a bit-precise integer type is converted to
8188 // the corresponding bit-precise integer type. (The rest is the same as in
8189 // C11.)
8190 if (QualType QT = Field->getType(); QT->isBitIntType())
8191 return QT;
8192
8193 if (BitWidth < IntSize)
8194 return IntTy;
8195
8196 if (BitWidth == IntSize)
8197 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
8198
8199 // Bit-fields wider than int are not subject to promotions, and therefore act
8200 // like the base type. GCC has some weird bugs in this area that we
8201 // deliberately do not follow (GCC follows a pre-standard resolution to
8202 // C's DR315 which treats bit-width as being part of the type, and this leaks
8203 // into their semantics in some cases).
8204 return {};
8205}
8206
8207/// getPromotedIntegerType - Returns the type that Promotable will
8208/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
8209/// integer type.
8211 assert(!Promotable.isNull());
8212 assert(isPromotableIntegerType(Promotable));
8213 if (const auto *ED = Promotable->getAsEnumDecl())
8214 return ED->getPromotionType();
8215
8216 if (const auto *BT = Promotable->getAs<BuiltinType>()) {
8217 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
8218 // (3.9.1) can be converted to a prvalue of the first of the following
8219 // types that can represent all the values of its underlying type:
8220 // int, unsigned int, long int, unsigned long int, long long int, or
8221 // unsigned long long int [...]
8222 // FIXME: Is there some better way to compute this?
8223 if (BT->getKind() == BuiltinType::WChar_S ||
8224 BT->getKind() == BuiltinType::WChar_U ||
8225 BT->getKind() == BuiltinType::Char8 ||
8226 BT->getKind() == BuiltinType::Char16 ||
8227 BT->getKind() == BuiltinType::Char32) {
8228 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
8229 uint64_t FromSize = getTypeSize(BT);
8230 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
8232 for (const auto &PT : PromoteTypes) {
8233 uint64_t ToSize = getTypeSize(PT);
8234 if (FromSize < ToSize ||
8235 (FromSize == ToSize && FromIsSigned == PT->isSignedIntegerType()))
8236 return PT;
8237 }
8238 llvm_unreachable("char type should fit into long long");
8239 }
8240 }
8241
8242 // At this point, we should have a signed or unsigned integer type.
8243 if (Promotable->isSignedIntegerType())
8244 return IntTy;
8245 uint64_t PromotableSize = getIntWidth(Promotable);
8246 uint64_t IntSize = getIntWidth(IntTy);
8247 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
8248 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
8249}
8250
8251/// Recurses in pointer/array types until it finds an objc retainable
8252/// type and returns its ownership.
8254 while (!T.isNull()) {
8255 if (T.getObjCLifetime() != Qualifiers::OCL_None)
8256 return T.getObjCLifetime();
8257 if (T->isArrayType())
8259 else if (const auto *PT = T->getAs<PointerType>())
8260 T = PT->getPointeeType();
8261 else if (const auto *RT = T->getAs<ReferenceType>())
8262 T = RT->getPointeeType();
8263 else
8264 break;
8265 }
8266
8267 return Qualifiers::OCL_None;
8268}
8269
8270static const Type *getIntegerTypeForEnum(const EnumType *ET) {
8271 // Incomplete enum types are not treated as integer types.
8272 // FIXME: In C++, enum types are never integer types.
8273 const EnumDecl *ED = ET->getDecl()->getDefinitionOrSelf();
8274 if (ED->isComplete() && !ED->isScoped())
8275 return ED->getIntegerType().getTypePtr();
8276 return nullptr;
8277}
8278
8279/// getIntegerTypeOrder - Returns the highest ranked integer type:
8280/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
8281/// LHS < RHS, return -1.
8283 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
8284 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
8285
8286 // Unwrap enums to their underlying type.
8287 if (const auto *ET = dyn_cast<EnumType>(LHSC))
8288 LHSC = getIntegerTypeForEnum(ET);
8289 if (const auto *ET = dyn_cast<EnumType>(RHSC))
8290 RHSC = getIntegerTypeForEnum(ET);
8291
8292 if (LHSC == RHSC) return 0;
8293
8294 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
8295 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
8296
8297 unsigned LHSRank = getIntegerRank(LHSC);
8298 unsigned RHSRank = getIntegerRank(RHSC);
8299
8300 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
8301 if (LHSRank == RHSRank) return 0;
8302 return LHSRank > RHSRank ? 1 : -1;
8303 }
8304
8305 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
8306 if (LHSUnsigned) {
8307 // If the unsigned [LHS] type is larger, return it.
8308 if (LHSRank >= RHSRank)
8309 return 1;
8310
8311 // If the signed type can represent all values of the unsigned type, it
8312 // wins. Because we are dealing with 2's complement and types that are
8313 // powers of two larger than each other, this is always safe.
8314 return -1;
8315 }
8316
8317 // If the unsigned [RHS] type is larger, return it.
8318 if (RHSRank >= LHSRank)
8319 return -1;
8320
8321 // If the signed type can represent all values of the unsigned type, it
8322 // wins. Because we are dealing with 2's complement and types that are
8323 // powers of two larger than each other, this is always safe.
8324 return 1;
8325}
8326
8328 if (CFConstantStringTypeDecl)
8329 return CFConstantStringTypeDecl;
8330
8331 assert(!CFConstantStringTagDecl &&
8332 "tag and typedef should be initialized together");
8333 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
8334 CFConstantStringTagDecl->startDefinition();
8335
8336 struct {
8337 QualType Type;
8338 const char *Name;
8339 } Fields[5];
8340 unsigned Count = 0;
8341
8342 /// Objective-C ABI
8343 ///
8344 /// typedef struct __NSConstantString_tag {
8345 /// const int *isa;
8346 /// int flags;
8347 /// const char *str;
8348 /// long length;
8349 /// } __NSConstantString;
8350 ///
8351 /// Swift ABI (4.1, 4.2)
8352 ///
8353 /// typedef struct __NSConstantString_tag {
8354 /// uintptr_t _cfisa;
8355 /// uintptr_t _swift_rc;
8356 /// _Atomic(uint64_t) _cfinfoa;
8357 /// const char *_ptr;
8358 /// uint32_t _length;
8359 /// } __NSConstantString;
8360 ///
8361 /// Swift ABI (5.0)
8362 ///
8363 /// typedef struct __NSConstantString_tag {
8364 /// uintptr_t _cfisa;
8365 /// uintptr_t _swift_rc;
8366 /// _Atomic(uint64_t) _cfinfoa;
8367 /// const char *_ptr;
8368 /// uintptr_t _length;
8369 /// } __NSConstantString;
8370
8371 const auto CFRuntime = getLangOpts().CFRuntime;
8372 if (static_cast<unsigned>(CFRuntime) <
8373 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
8374 Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
8375 Fields[Count++] = { IntTy, "flags" };
8376 Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
8377 Fields[Count++] = { LongTy, "length" };
8378 } else {
8379 Fields[Count++] = { getUIntPtrType(), "_cfisa" };
8380 Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
8381 Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
8382 Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
8385 Fields[Count++] = { IntTy, "_ptr" };
8386 else
8387 Fields[Count++] = { getUIntPtrType(), "_ptr" };
8388 }
8389
8390 // Create fields
8391 for (unsigned i = 0; i < Count; ++i) {
8392 FieldDecl *Field =
8393 FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
8394 SourceLocation(), &Idents.get(Fields[i].Name),
8395 Fields[i].Type, /*TInfo=*/nullptr,
8396 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
8397 Field->setAccess(AS_public);
8398 CFConstantStringTagDecl->addDecl(Field);
8399 }
8400
8401 CFConstantStringTagDecl->completeDefinition();
8402 // This type is designed to be compatible with NSConstantString, but cannot
8403 // use the same name, since NSConstantString is an interface.
8404 CanQualType tagType = getCanonicalTagType(CFConstantStringTagDecl);
8405 CFConstantStringTypeDecl =
8406 buildImplicitTypedef(tagType, "__NSConstantString");
8407
8408 return CFConstantStringTypeDecl;
8409}
8410
8412 if (!CFConstantStringTagDecl)
8413 getCFConstantStringDecl(); // Build the tag and the typedef.
8414 return CFConstantStringTagDecl;
8415}
8416
8417// getCFConstantStringType - Return the type used for constant CFStrings.
8422
8424 if (ObjCSuperType.isNull()) {
8425 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
8426 getTranslationUnitDecl()->addDecl(ObjCSuperTypeDecl);
8427 ObjCSuperType = getCanonicalTagType(ObjCSuperTypeDecl);
8428 }
8429 return ObjCSuperType;
8430}
8431
8433 const auto *TT = T->castAs<TypedefType>();
8434 CFConstantStringTypeDecl = cast<TypedefDecl>(TT->getDecl());
8435 CFConstantStringTagDecl = TT->castAsRecordDecl();
8436}
8437
8439 if (BlockDescriptorType)
8440 return getCanonicalTagType(BlockDescriptorType);
8441
8442 RecordDecl *RD;
8443 // FIXME: Needs the FlagAppleBlock bit.
8444 RD = buildImplicitRecord("__block_descriptor");
8445 RD->startDefinition();
8446
8447 QualType FieldTypes[] = {
8450 };
8451
8452 static const char *const FieldNames[] = {
8453 "reserved",
8454 "Size"
8455 };
8456
8457 for (size_t i = 0; i < 2; ++i) {
8459 *this, RD, SourceLocation(), SourceLocation(),
8460 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
8461 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
8462 Field->setAccess(AS_public);
8463 RD->addDecl(Field);
8464 }
8465
8466 RD->completeDefinition();
8467
8468 BlockDescriptorType = RD;
8469
8470 return getCanonicalTagType(BlockDescriptorType);
8471}
8472
8474 if (BlockDescriptorExtendedType)
8475 return getCanonicalTagType(BlockDescriptorExtendedType);
8476
8477 RecordDecl *RD;
8478 // FIXME: Needs the FlagAppleBlock bit.
8479 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
8480 RD->startDefinition();
8481
8482 QualType FieldTypes[] = {
8487 };
8488
8489 static const char *const FieldNames[] = {
8490 "reserved",
8491 "Size",
8492 "CopyFuncPtr",
8493 "DestroyFuncPtr"
8494 };
8495
8496 for (size_t i = 0; i < 4; ++i) {
8498 *this, RD, SourceLocation(), SourceLocation(),
8499 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
8500 /*BitWidth=*/nullptr,
8501 /*Mutable=*/false, ICIS_NoInit);
8502 Field->setAccess(AS_public);
8503 RD->addDecl(Field);
8504 }
8505
8506 RD->completeDefinition();
8507
8508 BlockDescriptorExtendedType = RD;
8509 return getCanonicalTagType(BlockDescriptorExtendedType);
8510}
8511
8513 const auto *BT = dyn_cast<BuiltinType>(T);
8514
8515 if (!BT) {
8516 if (isa<PipeType>(T))
8517 return OCLTK_Pipe;
8518
8519 return OCLTK_Default;
8520 }
8521
8522 switch (BT->getKind()) {
8523#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8524 case BuiltinType::Id: \
8525 return OCLTK_Image;
8526#include "clang/Basic/OpenCLImageTypes.def"
8527
8528 case BuiltinType::OCLClkEvent:
8529 return OCLTK_ClkEvent;
8530
8531 case BuiltinType::OCLEvent:
8532 return OCLTK_Event;
8533
8534 case BuiltinType::OCLQueue:
8535 return OCLTK_Queue;
8536
8537 case BuiltinType::OCLReserveID:
8538 return OCLTK_ReserveID;
8539
8540 case BuiltinType::OCLSampler:
8541 return OCLTK_Sampler;
8542
8543 default:
8544 return OCLTK_Default;
8545 }
8546}
8547
8549 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
8550}
8551
8552/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
8553/// requires copy/dispose. Note that this must match the logic
8554/// in buildByrefHelpers.
8556 const VarDecl *D) {
8557 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
8558 const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
8559 if (!copyExpr && record->hasTrivialDestructor()) return false;
8560
8561 return true;
8562 }
8563
8565 return true;
8566
8567 // The block needs copy/destroy helpers if Ty is non-trivial to destructively
8568 // move or destroy.
8570 return true;
8571
8572 if (!Ty->isObjCRetainableType()) return false;
8573
8574 Qualifiers qs = Ty.getQualifiers();
8575
8576 // If we have lifetime, that dominates.
8577 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
8578 switch (lifetime) {
8579 case Qualifiers::OCL_None: llvm_unreachable("impossible");
8580
8581 // These are just bits as far as the runtime is concerned.
8584 return false;
8585
8586 // These cases should have been taken care of when checking the type's
8587 // non-triviality.
8590 llvm_unreachable("impossible");
8591 }
8592 llvm_unreachable("fell out of lifetime switch!");
8593 }
8594 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
8596}
8597
8599 Qualifiers::ObjCLifetime &LifeTime,
8600 bool &HasByrefExtendedLayout) const {
8601 if (!getLangOpts().ObjC ||
8602 getLangOpts().getGC() != LangOptions::NonGC)
8603 return false;
8604
8605 HasByrefExtendedLayout = false;
8606 if (Ty->isRecordType()) {
8607 HasByrefExtendedLayout = true;
8608 LifeTime = Qualifiers::OCL_None;
8609 } else if ((LifeTime = Ty.getObjCLifetime())) {
8610 // Honor the ARC qualifiers.
8611 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
8612 // The MRR rule.
8614 } else {
8615 LifeTime = Qualifiers::OCL_None;
8616 }
8617 return true;
8618}
8619
8621 assert(Target && "Expected target to be initialized");
8622 const llvm::Triple &T = Target->getTriple();
8623 // Windows is LLP64 rather than LP64
8624 if (T.isOSWindows() && T.isArch64Bit())
8625 return UnsignedLongLongTy;
8626 return UnsignedLongTy;
8627}
8628
8630 assert(Target && "Expected target to be initialized");
8631 const llvm::Triple &T = Target->getTriple();
8632 // Windows is LLP64 rather than LP64
8633 if (T.isOSWindows() && T.isArch64Bit())
8634 return LongLongTy;
8635 return LongTy;
8636}
8637
8639 if (!ObjCInstanceTypeDecl)
8640 ObjCInstanceTypeDecl =
8641 buildImplicitTypedef(getObjCIdType(), "instancetype");
8642 return ObjCInstanceTypeDecl;
8643}
8644
8645// This returns true if a type has been typedefed to BOOL:
8646// typedef <type> BOOL;
8648 if (const auto *TT = dyn_cast<TypedefType>(T))
8649 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
8650 return II->isStr("BOOL");
8651
8652 return false;
8653}
8654
8655/// getObjCEncodingTypeSize returns size of type for objective-c encoding
8656/// purpose.
8658 if (!type->isIncompleteArrayType() && type->isIncompleteType())
8659 return CharUnits::Zero();
8660
8662
8663 // Make all integer and enum types at least as large as an int
8664 if (sz.isPositive() && type->isIntegralOrEnumerationType())
8665 sz = std::max(sz, getTypeSizeInChars(IntTy));
8666 // Treat arrays as pointers, since that's how they're passed in.
8667 else if (type->isArrayType())
8669 return sz;
8670}
8671
8678
8681 if (!VD->isInline())
8683
8684 // In almost all cases, it's a weak definition.
8685 auto *First = VD->getFirstDecl();
8686 if (First->isInlineSpecified() || !First->isStaticDataMember())
8688
8689 // If there's a file-context declaration in this translation unit, it's a
8690 // non-discardable definition.
8691 for (auto *D : VD->redecls())
8693 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
8695
8696 // If we've not seen one yet, we don't know.
8698}
8699
8700static std::string charUnitsToString(const CharUnits &CU) {
8701 return llvm::itostr(CU.getQuantity());
8702}
8703
8704/// getObjCEncodingForBlock - Return the encoded type for this block
8705/// declaration.
8707 std::string S;
8708
8709 const BlockDecl *Decl = Expr->getBlockDecl();
8710 QualType BlockTy =
8712 QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType();
8713 // Encode result type.
8714 if (getLangOpts().EncodeExtendedBlockSig)
8716 true /*Extended*/);
8717 else
8718 getObjCEncodingForType(BlockReturnTy, S);
8719 // Compute size of all parameters.
8720 // Start with computing size of a pointer in number of bytes.
8721 // FIXME: There might(should) be a better way of doing this computation!
8723 CharUnits ParmOffset = PtrSize;
8724 for (auto *PI : Decl->parameters()) {
8725 QualType PType = PI->getType();
8727 if (sz.isZero())
8728 continue;
8729 assert(sz.isPositive() && "BlockExpr - Incomplete param type");
8730 ParmOffset += sz;
8731 }
8732 // Size of the argument frame
8733 S += charUnitsToString(ParmOffset);
8734 // Block pointer and offset.
8735 S += "@?0";
8736
8737 // Argument types.
8738 ParmOffset = PtrSize;
8739 for (auto *PVDecl : Decl->parameters()) {
8740 QualType PType = PVDecl->getOriginalType();
8741 if (const auto *AT =
8742 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8743 // Use array's original type only if it has known number of
8744 // elements.
8745 if (!isa<ConstantArrayType>(AT))
8746 PType = PVDecl->getType();
8747 } else if (PType->isFunctionType())
8748 PType = PVDecl->getType();
8749 if (getLangOpts().EncodeExtendedBlockSig)
8751 S, true /*Extended*/);
8752 else
8753 getObjCEncodingForType(PType, S);
8754 S += charUnitsToString(ParmOffset);
8755 ParmOffset += getObjCEncodingTypeSize(PType);
8756 }
8757
8758 return S;
8759}
8760
8761std::string
8763 std::string S;
8764 // Encode result type.
8765 getObjCEncodingForType(Decl->getReturnType(), S);
8766 CharUnits ParmOffset;
8767 // Compute size of all parameters.
8768 for (auto *PI : Decl->parameters()) {
8769 QualType PType = PI->getType();
8771 if (sz.isZero())
8772 continue;
8773
8774 assert(sz.isPositive() &&
8775 "getObjCEncodingForFunctionDecl - Incomplete param type");
8776 ParmOffset += sz;
8777 }
8778 S += charUnitsToString(ParmOffset);
8779 ParmOffset = CharUnits::Zero();
8780
8781 // Argument types.
8782 for (auto *PVDecl : Decl->parameters()) {
8783 QualType PType = PVDecl->getOriginalType();
8784 if (const auto *AT =
8785 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8786 // Use array's original type only if it has known number of
8787 // elements.
8788 if (!isa<ConstantArrayType>(AT))
8789 PType = PVDecl->getType();
8790 } else if (PType->isFunctionType())
8791 PType = PVDecl->getType();
8792 getObjCEncodingForType(PType, S);
8793 S += charUnitsToString(ParmOffset);
8794 ParmOffset += getObjCEncodingTypeSize(PType);
8795 }
8796
8797 return S;
8798}
8799
8800/// getObjCEncodingForMethodParameter - Return the encoded type for a single
8801/// method parameter or return type. If Extended, include class names and
8802/// block object types.
8804 QualType T, std::string& S,
8805 bool Extended) const {
8806 // Encode type qualifier, 'in', 'inout', etc. for the parameter.
8808 // Encode parameter type.
8809 ObjCEncOptions Options = ObjCEncOptions()
8810 .setExpandPointedToStructures()
8811 .setExpandStructures()
8812 .setIsOutermostType();
8813 if (Extended)
8814 Options.setEncodeBlockParameters().setEncodeClassNames();
8815 getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr);
8816}
8817
8818/// getObjCEncodingForMethodDecl - Return the encoded type for this method
8819/// declaration.
8821 bool Extended) const {
8822 // FIXME: This is not very efficient.
8823 // Encode return type.
8824 std::string S;
8825 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
8826 Decl->getReturnType(), S, Extended);
8827 // Compute size of all parameters.
8828 // Start with computing size of a pointer in number of bytes.
8829 // FIXME: There might(should) be a better way of doing this computation!
8831 // The first two arguments (self and _cmd) are pointers; account for
8832 // their size.
8833 CharUnits ParmOffset = 2 * PtrSize;
8834 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
8835 E = Decl->sel_param_end(); PI != E; ++PI) {
8836 QualType PType = (*PI)->getType();
8838 if (sz.isZero())
8839 continue;
8840
8841 assert(sz.isPositive() &&
8842 "getObjCEncodingForMethodDecl - Incomplete param type");
8843 ParmOffset += sz;
8844 }
8845 S += charUnitsToString(ParmOffset);
8846 S += "@0:";
8847 S += charUnitsToString(PtrSize);
8848
8849 // Argument types.
8850 ParmOffset = 2 * PtrSize;
8851 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
8852 E = Decl->sel_param_end(); PI != E; ++PI) {
8853 const ParmVarDecl *PVDecl = *PI;
8854 QualType PType = PVDecl->getOriginalType();
8855 if (const auto *AT =
8856 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8857 // Use array's original type only if it has known number of
8858 // elements.
8859 if (!isa<ConstantArrayType>(AT))
8860 PType = PVDecl->getType();
8861 } else if (PType->isFunctionType())
8862 PType = PVDecl->getType();
8864 PType, S, Extended);
8865 S += charUnitsToString(ParmOffset);
8866 ParmOffset += getObjCEncodingTypeSize(PType);
8867 }
8868
8869 return S;
8870}
8871
8874 const ObjCPropertyDecl *PD,
8875 const Decl *Container) const {
8876 if (!Container)
8877 return nullptr;
8878 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
8879 for (auto *PID : CID->property_impls())
8880 if (PID->getPropertyDecl() == PD)
8881 return PID;
8882 } else {
8883 const auto *OID = cast<ObjCImplementationDecl>(Container);
8884 for (auto *PID : OID->property_impls())
8885 if (PID->getPropertyDecl() == PD)
8886 return PID;
8887 }
8888 return nullptr;
8889}
8890
8891/// getObjCEncodingForPropertyDecl - Return the encoded type for this
8892/// property declaration. If non-NULL, Container must be either an
8893/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
8894/// NULL when getting encodings for protocol properties.
8895/// Property attributes are stored as a comma-delimited C string. The simple
8896/// attributes readonly and bycopy are encoded as single characters. The
8897/// parametrized attributes, getter=name, setter=name, and ivar=name, are
8898/// encoded as single characters, followed by an identifier. Property types
8899/// are also encoded as a parametrized attribute. The characters used to encode
8900/// these attributes are defined by the following enumeration:
8901/// @code
8902/// enum PropertyAttributes {
8903/// kPropertyReadOnly = 'R', // property is read-only.
8904/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
8905/// kPropertyByref = '&', // property is a reference to the value last assigned
8906/// kPropertyDynamic = 'D', // property is dynamic
8907/// kPropertyGetter = 'G', // followed by getter selector name
8908/// kPropertySetter = 'S', // followed by setter selector name
8909/// kPropertyInstanceVariable = 'V' // followed by instance variable name
8910/// kPropertyType = 'T' // followed by old-style type encoding.
8911/// kPropertyWeak = 'W' // 'weak' property
8912/// kPropertyStrong = 'P' // property GC'able
8913/// kPropertyNonAtomic = 'N' // property non-atomic
8914/// kPropertyOptional = '?' // property optional
8915/// };
8916/// @endcode
8917std::string
8919 const Decl *Container) const {
8920 // Collect information from the property implementation decl(s).
8921 bool Dynamic = false;
8922 ObjCPropertyImplDecl *SynthesizePID = nullptr;
8923
8924 if (ObjCPropertyImplDecl *PropertyImpDecl =
8926 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
8927 Dynamic = true;
8928 else
8929 SynthesizePID = PropertyImpDecl;
8930 }
8931
8932 // FIXME: This is not very efficient.
8933 std::string S = "T";
8934
8935 // Encode result type.
8936 // GCC has some special rules regarding encoding of properties which
8937 // closely resembles encoding of ivars.
8939
8940 if (PD->isOptional())
8941 S += ",?";
8942
8943 if (PD->isReadOnly()) {
8944 S += ",R";
8946 S += ",C";
8948 S += ",&";
8950 S += ",W";
8951 } else {
8952 switch (PD->getSetterKind()) {
8953 case ObjCPropertyDecl::Assign: break;
8954 case ObjCPropertyDecl::Copy: S += ",C"; break;
8955 case ObjCPropertyDecl::Retain: S += ",&"; break;
8956 case ObjCPropertyDecl::Weak: S += ",W"; break;
8957 }
8958 }
8959
8960 // It really isn't clear at all what this means, since properties
8961 // are "dynamic by default".
8962 if (Dynamic)
8963 S += ",D";
8964
8966 S += ",N";
8967
8969 S += ",G";
8970 S += PD->getGetterName().getAsString();
8971 }
8972
8974 S += ",S";
8975 S += PD->getSetterName().getAsString();
8976 }
8977
8978 if (SynthesizePID) {
8979 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
8980 S += ",V";
8981 S += OID->getNameAsString();
8982 }
8983
8984 // FIXME: OBJCGC: weak & strong
8985 return S;
8986}
8987
8988/// getLegacyIntegralTypeEncoding -
8989/// Another legacy compatibility encoding: 32-bit longs are encoded as
8990/// 'l' or 'L' , but not always. For typedefs, we need to use
8991/// 'i' or 'I' instead if encoding a struct field, or a pointer!
8993 if (PointeeTy->getAs<TypedefType>()) {
8994 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
8995 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
8996 PointeeTy = UnsignedIntTy;
8997 else
8998 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
8999 PointeeTy = IntTy;
9000 }
9001 }
9002}
9003
9005 const FieldDecl *Field,
9006 QualType *NotEncodedT) const {
9007 // We follow the behavior of gcc, expanding structures which are
9008 // directly pointed to, and expanding embedded structures. Note that
9009 // these rules are sufficient to prevent recursive encoding of the
9010 // same type.
9011 getObjCEncodingForTypeImpl(T, S,
9012 ObjCEncOptions()
9013 .setExpandPointedToStructures()
9014 .setExpandStructures()
9015 .setIsOutermostType(),
9016 Field, NotEncodedT);
9017}
9018
9020 std::string& S) const {
9021 // Encode result type.
9022 // GCC has some special rules regarding encoding of properties which
9023 // closely resembles encoding of ivars.
9024 getObjCEncodingForTypeImpl(T, S,
9025 ObjCEncOptions()
9026 .setExpandPointedToStructures()
9027 .setExpandStructures()
9028 .setIsOutermostType()
9029 .setEncodingProperty(),
9030 /*Field=*/nullptr);
9031}
9032
9034 const BuiltinType *BT) {
9035 BuiltinType::Kind kind = BT->getKind();
9036 switch (kind) {
9037 case BuiltinType::Void: return 'v';
9038 case BuiltinType::Bool: return 'B';
9039 case BuiltinType::Char8:
9040 case BuiltinType::Char_U:
9041 case BuiltinType::UChar: return 'C';
9042 case BuiltinType::Char16:
9043 case BuiltinType::UShort: return 'S';
9044 case BuiltinType::Char32:
9045 case BuiltinType::UInt: return 'I';
9046 case BuiltinType::ULong:
9047 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
9048 case BuiltinType::UInt128: return 'T';
9049 case BuiltinType::ULongLong: return 'Q';
9050 case BuiltinType::Char_S:
9051 case BuiltinType::SChar: return 'c';
9052 case BuiltinType::Short: return 's';
9053 case BuiltinType::WChar_S:
9054 case BuiltinType::WChar_U:
9055 case BuiltinType::Int: return 'i';
9056 case BuiltinType::Long:
9057 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
9058 case BuiltinType::LongLong: return 'q';
9059 case BuiltinType::Int128: return 't';
9060 case BuiltinType::Float: return 'f';
9061 case BuiltinType::Double: return 'd';
9062 case BuiltinType::LongDouble: return 'D';
9063 case BuiltinType::NullPtr: return '*'; // like char*
9064
9065 case BuiltinType::BFloat16:
9066 case BuiltinType::Float16:
9067 case BuiltinType::Float128:
9068 case BuiltinType::Ibm128:
9069 case BuiltinType::Half:
9070 case BuiltinType::ShortAccum:
9071 case BuiltinType::Accum:
9072 case BuiltinType::LongAccum:
9073 case BuiltinType::UShortAccum:
9074 case BuiltinType::UAccum:
9075 case BuiltinType::ULongAccum:
9076 case BuiltinType::ShortFract:
9077 case BuiltinType::Fract:
9078 case BuiltinType::LongFract:
9079 case BuiltinType::UShortFract:
9080 case BuiltinType::UFract:
9081 case BuiltinType::ULongFract:
9082 case BuiltinType::SatShortAccum:
9083 case BuiltinType::SatAccum:
9084 case BuiltinType::SatLongAccum:
9085 case BuiltinType::SatUShortAccum:
9086 case BuiltinType::SatUAccum:
9087 case BuiltinType::SatULongAccum:
9088 case BuiltinType::SatShortFract:
9089 case BuiltinType::SatFract:
9090 case BuiltinType::SatLongFract:
9091 case BuiltinType::SatUShortFract:
9092 case BuiltinType::SatUFract:
9093 case BuiltinType::SatULongFract:
9094 // FIXME: potentially need @encodes for these!
9095 return ' ';
9096
9097#define SVE_TYPE(Name, Id, SingletonId) \
9098 case BuiltinType::Id:
9099#include "clang/Basic/AArch64ACLETypes.def"
9100#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9101#include "clang/Basic/RISCVVTypes.def"
9102#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9103#include "clang/Basic/WebAssemblyReferenceTypes.def"
9104#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
9105#include "clang/Basic/AMDGPUTypes.def"
9106 {
9107 DiagnosticsEngine &Diags = C->getDiagnostics();
9108 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
9109 "cannot yet @encode type %0");
9110 Diags.Report(DiagID) << BT->getName(C->getPrintingPolicy());
9111 return ' ';
9112 }
9113
9114 case BuiltinType::ObjCId:
9115 case BuiltinType::ObjCClass:
9116 case BuiltinType::ObjCSel:
9117 llvm_unreachable("@encoding ObjC primitive type");
9118
9119 // OpenCL and placeholder types don't need @encodings.
9120#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
9121 case BuiltinType::Id:
9122#include "clang/Basic/OpenCLImageTypes.def"
9123#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
9124 case BuiltinType::Id:
9125#include "clang/Basic/OpenCLExtensionTypes.def"
9126 case BuiltinType::OCLEvent:
9127 case BuiltinType::OCLClkEvent:
9128 case BuiltinType::OCLQueue:
9129 case BuiltinType::OCLReserveID:
9130 case BuiltinType::OCLSampler:
9131 case BuiltinType::Dependent:
9132#define PPC_VECTOR_TYPE(Name, Id, Size) \
9133 case BuiltinType::Id:
9134#include "clang/Basic/PPCTypes.def"
9135#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9136#include "clang/Basic/HLSLIntangibleTypes.def"
9137#define BUILTIN_TYPE(KIND, ID)
9138#define PLACEHOLDER_TYPE(KIND, ID) \
9139 case BuiltinType::KIND:
9140#include "clang/AST/BuiltinTypes.def"
9141 llvm_unreachable("invalid builtin type for @encode");
9142 }
9143 llvm_unreachable("invalid BuiltinType::Kind value");
9144}
9145
9146static char ObjCEncodingForEnumDecl(const ASTContext *C, const EnumDecl *ED) {
9148
9149 // The encoding of an non-fixed enum type is always 'i', regardless of size.
9150 if (!Enum->isFixed())
9151 return 'i';
9152
9153 // The encoding of a fixed enum type matches its fixed underlying type.
9154 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
9156}
9157
9158static void EncodeBitField(const ASTContext *Ctx, std::string& S,
9159 QualType T, const FieldDecl *FD) {
9160 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
9161 S += 'b';
9162 // The NeXT runtime encodes bit fields as b followed by the number of bits.
9163 // The GNU runtime requires more information; bitfields are encoded as b,
9164 // then the offset (in bits) of the first element, then the type of the
9165 // bitfield, then the size in bits. For example, in this structure:
9166 //
9167 // struct
9168 // {
9169 // int integer;
9170 // int flags:2;
9171 // };
9172 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
9173 // runtime, but b32i2 for the GNU runtime. The reason for this extra
9174 // information is not especially sensible, but we're stuck with it for
9175 // compatibility with GCC, although providing it breaks anything that
9176 // actually uses runtime introspection and wants to work on both runtimes...
9177 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
9178 uint64_t Offset;
9179
9180 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
9181 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), IVD);
9182 } else {
9183 const RecordDecl *RD = FD->getParent();
9184 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
9185 Offset = RL.getFieldOffset(FD->getFieldIndex());
9186 }
9187
9188 S += llvm::utostr(Offset);
9189
9190 if (const auto *ET = T->getAsCanonical<EnumType>())
9191 S += ObjCEncodingForEnumDecl(Ctx, ET->getDecl());
9192 else {
9193 const auto *BT = T->castAs<BuiltinType>();
9194 S += getObjCEncodingForPrimitiveType(Ctx, BT);
9195 }
9196 }
9197 S += llvm::utostr(FD->getBitWidthValue());
9198}
9199
9200// Helper function for determining whether the encoded type string would include
9201// a template specialization type.
9203 bool VisitBasesAndFields) {
9204 T = T->getBaseElementTypeUnsafe();
9205
9206 if (auto *PT = T->getAs<PointerType>())
9208 PT->getPointeeType().getTypePtr(), false);
9209
9210 auto *CXXRD = T->getAsCXXRecordDecl();
9211
9212 if (!CXXRD)
9213 return false;
9214
9216 return true;
9217
9218 if (!CXXRD->hasDefinition() || !VisitBasesAndFields)
9219 return false;
9220
9221 for (const auto &B : CXXRD->bases())
9222 if (hasTemplateSpecializationInEncodedString(B.getType().getTypePtr(),
9223 true))
9224 return true;
9225
9226 for (auto *FD : CXXRD->fields())
9227 if (hasTemplateSpecializationInEncodedString(FD->getType().getTypePtr(),
9228 true))
9229 return true;
9230
9231 return false;
9232}
9233
9234// FIXME: Use SmallString for accumulating string.
9235void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
9236 const ObjCEncOptions Options,
9237 const FieldDecl *FD,
9238 QualType *NotEncodedT) const {
9240 switch (CT->getTypeClass()) {
9241 case Type::Builtin:
9242 case Type::Enum:
9243 if (FD && FD->isBitField())
9244 return EncodeBitField(this, S, T, FD);
9245 if (const auto *BT = dyn_cast<BuiltinType>(CT))
9246 S += getObjCEncodingForPrimitiveType(this, BT);
9247 else
9248 S += ObjCEncodingForEnumDecl(this, cast<EnumType>(CT)->getDecl());
9249 return;
9250
9251 case Type::Complex:
9252 S += 'j';
9253 getObjCEncodingForTypeImpl(T->castAs<ComplexType>()->getElementType(), S,
9254 ObjCEncOptions(),
9255 /*Field=*/nullptr);
9256 return;
9257
9258 case Type::Atomic:
9259 S += 'A';
9260 getObjCEncodingForTypeImpl(T->castAs<AtomicType>()->getValueType(), S,
9261 ObjCEncOptions(),
9262 /*Field=*/nullptr);
9263 return;
9264
9265 // encoding for pointer or reference types.
9266 case Type::Pointer:
9267 case Type::LValueReference:
9268 case Type::RValueReference: {
9269 QualType PointeeTy;
9270 if (isa<PointerType>(CT)) {
9271 const auto *PT = T->castAs<PointerType>();
9272 if (PT->isObjCSelType()) {
9273 S += ':';
9274 return;
9275 }
9276 PointeeTy = PT->getPointeeType();
9277 } else {
9278 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
9279 }
9280
9281 bool isReadOnly = false;
9282 // For historical/compatibility reasons, the read-only qualifier of the
9283 // pointee gets emitted _before_ the '^'. The read-only qualifier of
9284 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
9285 // Also, do not emit the 'r' for anything but the outermost type!
9286 if (T->getAs<TypedefType>()) {
9287 if (Options.IsOutermostType() && T.isConstQualified()) {
9288 isReadOnly = true;
9289 S += 'r';
9290 }
9291 } else if (Options.IsOutermostType()) {
9292 QualType P = PointeeTy;
9293 while (auto PT = P->getAs<PointerType>())
9294 P = PT->getPointeeType();
9295 if (P.isConstQualified()) {
9296 isReadOnly = true;
9297 S += 'r';
9298 }
9299 }
9300 if (isReadOnly) {
9301 // Another legacy compatibility encoding. Some ObjC qualifier and type
9302 // combinations need to be rearranged.
9303 // Rewrite "in const" from "nr" to "rn"
9304 if (StringRef(S).ends_with("nr"))
9305 S.replace(S.end()-2, S.end(), "rn");
9306 }
9307
9308 if (PointeeTy->isCharType()) {
9309 // char pointer types should be encoded as '*' unless it is a
9310 // type that has been typedef'd to 'BOOL'.
9311 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
9312 S += '*';
9313 return;
9314 }
9315 } else if (const auto *RTy = PointeeTy->getAsCanonical<RecordType>()) {
9316 const IdentifierInfo *II = RTy->getDecl()->getIdentifier();
9317 // GCC binary compat: Need to convert "struct objc_class *" to "#".
9318 if (II == &Idents.get("objc_class")) {
9319 S += '#';
9320 return;
9321 }
9322 // GCC binary compat: Need to convert "struct objc_object *" to "@".
9323 if (II == &Idents.get("objc_object")) {
9324 S += '@';
9325 return;
9326 }
9327 // If the encoded string for the class includes template names, just emit
9328 // "^v" for pointers to the class.
9329 if (getLangOpts().CPlusPlus &&
9330 (!getLangOpts().EncodeCXXClassTemplateSpec &&
9332 RTy, Options.ExpandPointedToStructures()))) {
9333 S += "^v";
9334 return;
9335 }
9336 // fall through...
9337 }
9338 S += '^';
9340
9341 ObjCEncOptions NewOptions;
9342 if (Options.ExpandPointedToStructures())
9343 NewOptions.setExpandStructures();
9344 getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions,
9345 /*Field=*/nullptr, NotEncodedT);
9346 return;
9347 }
9348
9349 case Type::ConstantArray:
9350 case Type::IncompleteArray:
9351 case Type::VariableArray: {
9352 const auto *AT = cast<ArrayType>(CT);
9353
9354 if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) {
9355 // Incomplete arrays are encoded as a pointer to the array element.
9356 S += '^';
9357
9358 getObjCEncodingForTypeImpl(
9359 AT->getElementType(), S,
9360 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD);
9361 } else {
9362 S += '[';
9363
9364 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
9365 S += llvm::utostr(CAT->getZExtSize());
9366 else {
9367 //Variable length arrays are encoded as a regular array with 0 elements.
9369 "Unknown array type!");
9370 S += '0';
9371 }
9372
9373 getObjCEncodingForTypeImpl(
9374 AT->getElementType(), S,
9375 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD,
9376 NotEncodedT);
9377 S += ']';
9378 }
9379 return;
9380 }
9381
9382 case Type::FunctionNoProto:
9383 case Type::FunctionProto:
9384 S += '?';
9385 return;
9386
9387 case Type::Record: {
9388 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
9389 S += RDecl->isUnion() ? '(' : '{';
9390 // Anonymous structures print as '?'
9391 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
9392 S += II->getName();
9393 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
9394 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
9395 llvm::raw_string_ostream OS(S);
9396 printTemplateArgumentList(OS, TemplateArgs.asArray(),
9398 }
9399 } else {
9400 S += '?';
9401 }
9402 if (Options.ExpandStructures()) {
9403 S += '=';
9404 if (!RDecl->isUnion()) {
9405 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
9406 } else {
9407 for (const auto *Field : RDecl->fields()) {
9408 if (FD) {
9409 S += '"';
9410 S += Field->getNameAsString();
9411 S += '"';
9412 }
9413
9414 // Special case bit-fields.
9415 if (Field->isBitField()) {
9416 getObjCEncodingForTypeImpl(Field->getType(), S,
9417 ObjCEncOptions().setExpandStructures(),
9418 Field);
9419 } else {
9420 QualType qt = Field->getType();
9422 getObjCEncodingForTypeImpl(
9423 qt, S,
9424 ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
9425 NotEncodedT);
9426 }
9427 }
9428 }
9429 }
9430 S += RDecl->isUnion() ? ')' : '}';
9431 return;
9432 }
9433
9434 case Type::BlockPointer: {
9435 const auto *BT = T->castAs<BlockPointerType>();
9436 S += "@?"; // Unlike a pointer-to-function, which is "^?".
9437 if (Options.EncodeBlockParameters()) {
9438 const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
9439
9440 S += '<';
9441 // Block return type
9442 getObjCEncodingForTypeImpl(FT->getReturnType(), S,
9443 Options.forComponentType(), FD, NotEncodedT);
9444 // Block self
9445 S += "@?";
9446 // Block parameters
9447 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
9448 for (const auto &I : FPT->param_types())
9449 getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD,
9450 NotEncodedT);
9451 }
9452 S += '>';
9453 }
9454 return;
9455 }
9456
9457 case Type::ObjCObject: {
9458 // hack to match legacy encoding of *id and *Class
9459 QualType Ty = getObjCObjectPointerType(CT);
9460 if (Ty->isObjCIdType()) {
9461 S += "{objc_object=}";
9462 return;
9463 }
9464 else if (Ty->isObjCClassType()) {
9465 S += "{objc_class=}";
9466 return;
9467 }
9468 // TODO: Double check to make sure this intentionally falls through.
9469 [[fallthrough]];
9470 }
9471
9472 case Type::ObjCInterface: {
9473 // Ignore protocol qualifiers when mangling at this level.
9474 // @encode(class_name)
9475 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
9476 S += '{';
9477 S += OI->getObjCRuntimeNameAsString();
9478 if (Options.ExpandStructures()) {
9479 S += '=';
9480 SmallVector<const ObjCIvarDecl*, 32> Ivars;
9481 DeepCollectObjCIvars(OI, true, Ivars);
9482 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
9483 const FieldDecl *Field = Ivars[i];
9484 if (Field->isBitField())
9485 getObjCEncodingForTypeImpl(Field->getType(), S,
9486 ObjCEncOptions().setExpandStructures(),
9487 Field);
9488 else
9489 getObjCEncodingForTypeImpl(Field->getType(), S,
9490 ObjCEncOptions().setExpandStructures(), FD,
9491 NotEncodedT);
9492 }
9493 }
9494 S += '}';
9495 return;
9496 }
9497
9498 case Type::ObjCObjectPointer: {
9499 const auto *OPT = T->castAs<ObjCObjectPointerType>();
9500 if (OPT->isObjCIdType()) {
9501 S += '@';
9502 return;
9503 }
9504
9505 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
9506 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
9507 // Since this is a binary compatibility issue, need to consult with
9508 // runtime folks. Fortunately, this is a *very* obscure construct.
9509 S += '#';
9510 return;
9511 }
9512
9513 if (OPT->isObjCQualifiedIdType()) {
9514 getObjCEncodingForTypeImpl(
9515 getObjCIdType(), S,
9516 Options.keepingOnly(ObjCEncOptions()
9517 .setExpandPointedToStructures()
9518 .setExpandStructures()),
9519 FD);
9520 if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
9521 // Note that we do extended encoding of protocol qualifier list
9522 // Only when doing ivar or property encoding.
9523 S += '"';
9524 for (const auto *I : OPT->quals()) {
9525 S += '<';
9526 S += I->getObjCRuntimeNameAsString();
9527 S += '>';
9528 }
9529 S += '"';
9530 }
9531 return;
9532 }
9533
9534 S += '@';
9535 if (OPT->getInterfaceDecl() &&
9536 (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
9537 S += '"';
9538 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
9539 for (const auto *I : OPT->quals()) {
9540 S += '<';
9541 S += I->getObjCRuntimeNameAsString();
9542 S += '>';
9543 }
9544 S += '"';
9545 }
9546 return;
9547 }
9548
9549 // gcc just blithely ignores member pointers.
9550 // FIXME: we should do better than that. 'M' is available.
9551 case Type::MemberPointer:
9552 // This matches gcc's encoding, even though technically it is insufficient.
9553 //FIXME. We should do a better job than gcc.
9554 case Type::Vector:
9555 case Type::ExtVector:
9556 // Until we have a coherent encoding of these three types, issue warning.
9557 if (NotEncodedT)
9558 *NotEncodedT = T;
9559 return;
9560
9561 case Type::ConstantMatrix:
9562 if (NotEncodedT)
9563 *NotEncodedT = T;
9564 return;
9565
9566 case Type::BitInt:
9567 if (NotEncodedT)
9568 *NotEncodedT = T;
9569 return;
9570
9571 // We could see an undeduced auto type here during error recovery.
9572 // Just ignore it.
9573 case Type::Auto:
9574 case Type::DeducedTemplateSpecialization:
9575 return;
9576
9577 case Type::HLSLAttributedResource:
9578 case Type::HLSLInlineSpirv:
9579 llvm_unreachable("unexpected type");
9580
9581 case Type::ArrayParameter:
9582 case Type::Pipe:
9583#define ABSTRACT_TYPE(KIND, BASE)
9584#define TYPE(KIND, BASE)
9585#define DEPENDENT_TYPE(KIND, BASE) \
9586 case Type::KIND:
9587#define NON_CANONICAL_TYPE(KIND, BASE) \
9588 case Type::KIND:
9589#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
9590 case Type::KIND:
9591#include "clang/AST/TypeNodes.inc"
9592 llvm_unreachable("@encode for dependent type!");
9593 }
9594 llvm_unreachable("bad type kind!");
9595}
9596
9597void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
9598 std::string &S,
9599 const FieldDecl *FD,
9600 bool includeVBases,
9601 QualType *NotEncodedT) const {
9602 assert(RDecl && "Expected non-null RecordDecl");
9603 assert(!RDecl->isUnion() && "Should not be called for unions");
9604 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
9605 return;
9606
9607 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
9608 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
9609 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
9610
9611 if (CXXRec) {
9612 for (const auto &BI : CXXRec->bases()) {
9613 if (!BI.isVirtual()) {
9614 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9615 if (base->isEmpty())
9616 continue;
9617 uint64_t offs = toBits(layout.getBaseClassOffset(base));
9618 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9619 std::make_pair(offs, base));
9620 }
9621 }
9622 }
9623
9624 for (FieldDecl *Field : RDecl->fields()) {
9625 if (!Field->isZeroLengthBitField() && Field->isZeroSize(*this))
9626 continue;
9627 uint64_t offs = layout.getFieldOffset(Field->getFieldIndex());
9628 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9629 std::make_pair(offs, Field));
9630 }
9631
9632 if (CXXRec && includeVBases) {
9633 for (const auto &BI : CXXRec->vbases()) {
9634 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9635 if (base->isEmpty())
9636 continue;
9637 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
9638 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
9639 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
9640 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
9641 std::make_pair(offs, base));
9642 }
9643 }
9644
9645 CharUnits size;
9646 if (CXXRec) {
9647 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
9648 } else {
9649 size = layout.getSize();
9650 }
9651
9652#ifndef NDEBUG
9653 uint64_t CurOffs = 0;
9654#endif
9655 std::multimap<uint64_t, NamedDecl *>::iterator
9656 CurLayObj = FieldOrBaseOffsets.begin();
9657
9658 if (CXXRec && CXXRec->isDynamicClass() &&
9659 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
9660 if (FD) {
9661 S += "\"_vptr$";
9662 std::string recname = CXXRec->getNameAsString();
9663 if (recname.empty()) recname = "?";
9664 S += recname;
9665 S += '"';
9666 }
9667 S += "^^?";
9668#ifndef NDEBUG
9669 CurOffs += getTypeSize(VoidPtrTy);
9670#endif
9671 }
9672
9673 if (!RDecl->hasFlexibleArrayMember()) {
9674 // Mark the end of the structure.
9675 uint64_t offs = toBits(size);
9676 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9677 std::make_pair(offs, nullptr));
9678 }
9679
9680 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
9681#ifndef NDEBUG
9682 assert(CurOffs <= CurLayObj->first);
9683 if (CurOffs < CurLayObj->first) {
9684 uint64_t padding = CurLayObj->first - CurOffs;
9685 // FIXME: There doesn't seem to be a way to indicate in the encoding that
9686 // packing/alignment of members is different that normal, in which case
9687 // the encoding will be out-of-sync with the real layout.
9688 // If the runtime switches to just consider the size of types without
9689 // taking into account alignment, we could make padding explicit in the
9690 // encoding (e.g. using arrays of chars). The encoding strings would be
9691 // longer then though.
9692 CurOffs += padding;
9693 }
9694#endif
9695
9696 NamedDecl *dcl = CurLayObj->second;
9697 if (!dcl)
9698 break; // reached end of structure.
9699
9700 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
9701 // We expand the bases without their virtual bases since those are going
9702 // in the initial structure. Note that this differs from gcc which
9703 // expands virtual bases each time one is encountered in the hierarchy,
9704 // making the encoding type bigger than it really is.
9705 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
9706 NotEncodedT);
9707 assert(!base->isEmpty());
9708#ifndef NDEBUG
9709 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
9710#endif
9711 } else {
9712 const auto *field = cast<FieldDecl>(dcl);
9713 if (FD) {
9714 S += '"';
9715 S += field->getNameAsString();
9716 S += '"';
9717 }
9718
9719 if (field->isBitField()) {
9720 EncodeBitField(this, S, field->getType(), field);
9721#ifndef NDEBUG
9722 CurOffs += field->getBitWidthValue();
9723#endif
9724 } else {
9725 QualType qt = field->getType();
9727 getObjCEncodingForTypeImpl(
9728 qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(),
9729 FD, NotEncodedT);
9730#ifndef NDEBUG
9731 CurOffs += getTypeSize(field->getType());
9732#endif
9733 }
9734 }
9735 }
9736}
9737
9739 std::string& S) const {
9740 if (QT & Decl::OBJC_TQ_In)
9741 S += 'n';
9742 if (QT & Decl::OBJC_TQ_Inout)
9743 S += 'N';
9744 if (QT & Decl::OBJC_TQ_Out)
9745 S += 'o';
9746 if (QT & Decl::OBJC_TQ_Bycopy)
9747 S += 'O';
9748 if (QT & Decl::OBJC_TQ_Byref)
9749 S += 'R';
9750 if (QT & Decl::OBJC_TQ_Oneway)
9751 S += 'V';
9752}
9753
9755 if (!ObjCIdDecl) {
9758 ObjCIdDecl = buildImplicitTypedef(T, "id");
9759 }
9760 return ObjCIdDecl;
9761}
9762
9764 if (!ObjCSelDecl) {
9766 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
9767 }
9768 return ObjCSelDecl;
9769}
9770
9772 if (!ObjCClassDecl) {
9775 ObjCClassDecl = buildImplicitTypedef(T, "Class");
9776 }
9777 return ObjCClassDecl;
9778}
9779
9781 if (!ObjCProtocolClassDecl) {
9782 ObjCProtocolClassDecl
9785 &Idents.get("Protocol"),
9786 /*typeParamList=*/nullptr,
9787 /*PrevDecl=*/nullptr,
9788 SourceLocation(), true);
9789 }
9790
9791 return ObjCProtocolClassDecl;
9792}
9793
9795 if (!getLangOpts().PointerAuthObjcInterfaceSel)
9796 return PointerAuthQualifier();
9798 getLangOpts().PointerAuthObjcInterfaceSelKey,
9799 /*isAddressDiscriminated=*/true, SelPointerConstantDiscriminator,
9801 /*isIsaPointer=*/false,
9802 /*authenticatesNullValues=*/false);
9803}
9804
9805//===----------------------------------------------------------------------===//
9806// __builtin_va_list Construction Functions
9807//===----------------------------------------------------------------------===//
9808
9810 StringRef Name) {
9811 // typedef char* __builtin[_ms]_va_list;
9812 QualType T = Context->getPointerType(Context->CharTy);
9813 return Context->buildImplicitTypedef(T, Name);
9814}
9815
9817 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
9818}
9819
9821 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
9822}
9823
9825 // typedef void* __builtin_va_list;
9826 QualType T = Context->getPointerType(Context->VoidTy);
9827 return Context->buildImplicitTypedef(T, "__builtin_va_list");
9828}
9829
9830static TypedefDecl *
9832 // struct __va_list
9833 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
9834 if (Context->getLangOpts().CPlusPlus) {
9835 // namespace std { struct __va_list {
9836 auto *NS = NamespaceDecl::Create(
9837 const_cast<ASTContext &>(*Context), Context->getTranslationUnitDecl(),
9838 /*Inline=*/false, SourceLocation(), SourceLocation(),
9839 &Context->Idents.get("std"),
9840 /*PrevDecl=*/nullptr, /*Nested=*/false);
9841 NS->setImplicit();
9843 }
9844
9845 VaListTagDecl->startDefinition();
9846
9847 const size_t NumFields = 5;
9848 QualType FieldTypes[NumFields];
9849 const char *FieldNames[NumFields];
9850
9851 // void *__stack;
9852 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
9853 FieldNames[0] = "__stack";
9854
9855 // void *__gr_top;
9856 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
9857 FieldNames[1] = "__gr_top";
9858
9859 // void *__vr_top;
9860 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
9861 FieldNames[2] = "__vr_top";
9862
9863 // int __gr_offs;
9864 FieldTypes[3] = Context->IntTy;
9865 FieldNames[3] = "__gr_offs";
9866
9867 // int __vr_offs;
9868 FieldTypes[4] = Context->IntTy;
9869 FieldNames[4] = "__vr_offs";
9870
9871 // Create fields
9872 for (unsigned i = 0; i < NumFields; ++i) {
9873 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
9877 &Context->Idents.get(FieldNames[i]),
9878 FieldTypes[i], /*TInfo=*/nullptr,
9879 /*BitWidth=*/nullptr,
9880 /*Mutable=*/false,
9881 ICIS_NoInit);
9882 Field->setAccess(AS_public);
9883 VaListTagDecl->addDecl(Field);
9884 }
9885 VaListTagDecl->completeDefinition();
9886 Context->VaListTagDecl = VaListTagDecl;
9887 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
9888
9889 // } __builtin_va_list;
9890 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
9891}
9892
9894 // typedef struct __va_list_tag {
9896
9897 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
9898 VaListTagDecl->startDefinition();
9899
9900 const size_t NumFields = 5;
9901 QualType FieldTypes[NumFields];
9902 const char *FieldNames[NumFields];
9903
9904 // unsigned char gpr;
9905 FieldTypes[0] = Context->UnsignedCharTy;
9906 FieldNames[0] = "gpr";
9907
9908 // unsigned char fpr;
9909 FieldTypes[1] = Context->UnsignedCharTy;
9910 FieldNames[1] = "fpr";
9911
9912 // unsigned short reserved;
9913 FieldTypes[2] = Context->UnsignedShortTy;
9914 FieldNames[2] = "reserved";
9915
9916 // void* overflow_arg_area;
9917 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
9918 FieldNames[3] = "overflow_arg_area";
9919
9920 // void* reg_save_area;
9921 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
9922 FieldNames[4] = "reg_save_area";
9923
9924 // Create fields
9925 for (unsigned i = 0; i < NumFields; ++i) {
9926 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
9929 &Context->Idents.get(FieldNames[i]),
9930 FieldTypes[i], /*TInfo=*/nullptr,
9931 /*BitWidth=*/nullptr,
9932 /*Mutable=*/false,
9933 ICIS_NoInit);
9934 Field->setAccess(AS_public);
9935 VaListTagDecl->addDecl(Field);
9936 }
9937 VaListTagDecl->completeDefinition();
9938 Context->VaListTagDecl = VaListTagDecl;
9939 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
9940
9941 // } __va_list_tag;
9942 TypedefDecl *VaListTagTypedefDecl =
9943 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
9944
9945 QualType VaListTagTypedefType =
9946 Context->getTypedefType(ElaboratedTypeKeyword::None,
9947 /*Qualifier=*/std::nullopt, VaListTagTypedefDecl);
9948
9949 // typedef __va_list_tag __builtin_va_list[1];
9950 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
9951 QualType VaListTagArrayType = Context->getConstantArrayType(
9952 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
9953 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
9954}
9955
9956static TypedefDecl *
9958 // struct __va_list_tag {
9960 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
9961 VaListTagDecl->startDefinition();
9962
9963 const size_t NumFields = 4;
9964 QualType FieldTypes[NumFields];
9965 const char *FieldNames[NumFields];
9966
9967 // unsigned gp_offset;
9968 FieldTypes[0] = Context->UnsignedIntTy;
9969 FieldNames[0] = "gp_offset";
9970
9971 // unsigned fp_offset;
9972 FieldTypes[1] = Context->UnsignedIntTy;
9973 FieldNames[1] = "fp_offset";
9974
9975 // void* overflow_arg_area;
9976 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
9977 FieldNames[2] = "overflow_arg_area";
9978
9979 // void* reg_save_area;
9980 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
9981 FieldNames[3] = "reg_save_area";
9982
9983 // Create fields
9984 for (unsigned i = 0; i < NumFields; ++i) {
9985 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
9989 &Context->Idents.get(FieldNames[i]),
9990 FieldTypes[i], /*TInfo=*/nullptr,
9991 /*BitWidth=*/nullptr,
9992 /*Mutable=*/false,
9993 ICIS_NoInit);
9994 Field->setAccess(AS_public);
9995 VaListTagDecl->addDecl(Field);
9996 }
9997 VaListTagDecl->completeDefinition();
9998 Context->VaListTagDecl = VaListTagDecl;
9999 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10000
10001 // };
10002
10003 // typedef struct __va_list_tag __builtin_va_list[1];
10004 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10005 QualType VaListTagArrayType = Context->getConstantArrayType(
10006 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
10007 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10008}
10009
10010static TypedefDecl *
10012 // struct __va_list
10013 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
10014 if (Context->getLangOpts().CPlusPlus) {
10015 // namespace std { struct __va_list {
10016 NamespaceDecl *NS;
10017 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
10018 Context->getTranslationUnitDecl(),
10019 /*Inline=*/false, SourceLocation(),
10020 SourceLocation(), &Context->Idents.get("std"),
10021 /*PrevDecl=*/nullptr, /*Nested=*/false);
10022 NS->setImplicit();
10023 VaListDecl->setDeclContext(NS);
10024 }
10025
10026 VaListDecl->startDefinition();
10027
10028 // void * __ap;
10029 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10030 VaListDecl,
10033 &Context->Idents.get("__ap"),
10034 Context->getPointerType(Context->VoidTy),
10035 /*TInfo=*/nullptr,
10036 /*BitWidth=*/nullptr,
10037 /*Mutable=*/false,
10038 ICIS_NoInit);
10039 Field->setAccess(AS_public);
10040 VaListDecl->addDecl(Field);
10041
10042 // };
10043 VaListDecl->completeDefinition();
10044 Context->VaListTagDecl = VaListDecl;
10045
10046 // typedef struct __va_list __builtin_va_list;
10047 CanQualType T = Context->getCanonicalTagType(VaListDecl);
10048 return Context->buildImplicitTypedef(T, "__builtin_va_list");
10049}
10050
10051static TypedefDecl *
10053 // struct __va_list_tag {
10055 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10056 VaListTagDecl->startDefinition();
10057
10058 const size_t NumFields = 4;
10059 QualType FieldTypes[NumFields];
10060 const char *FieldNames[NumFields];
10061
10062 // long __gpr;
10063 FieldTypes[0] = Context->LongTy;
10064 FieldNames[0] = "__gpr";
10065
10066 // long __fpr;
10067 FieldTypes[1] = Context->LongTy;
10068 FieldNames[1] = "__fpr";
10069
10070 // void *__overflow_arg_area;
10071 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10072 FieldNames[2] = "__overflow_arg_area";
10073
10074 // void *__reg_save_area;
10075 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
10076 FieldNames[3] = "__reg_save_area";
10077
10078 // Create fields
10079 for (unsigned i = 0; i < NumFields; ++i) {
10080 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10084 &Context->Idents.get(FieldNames[i]),
10085 FieldTypes[i], /*TInfo=*/nullptr,
10086 /*BitWidth=*/nullptr,
10087 /*Mutable=*/false,
10088 ICIS_NoInit);
10089 Field->setAccess(AS_public);
10090 VaListTagDecl->addDecl(Field);
10091 }
10092 VaListTagDecl->completeDefinition();
10093 Context->VaListTagDecl = VaListTagDecl;
10094 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10095
10096 // };
10097
10098 // typedef __va_list_tag __builtin_va_list[1];
10099 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10100 QualType VaListTagArrayType = Context->getConstantArrayType(
10101 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
10102
10103 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10104}
10105
10107 // typedef struct __va_list_tag {
10109 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10110 VaListTagDecl->startDefinition();
10111
10112 const size_t NumFields = 3;
10113 QualType FieldTypes[NumFields];
10114 const char *FieldNames[NumFields];
10115
10116 // void *CurrentSavedRegisterArea;
10117 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
10118 FieldNames[0] = "__current_saved_reg_area_pointer";
10119
10120 // void *SavedRegAreaEnd;
10121 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
10122 FieldNames[1] = "__saved_reg_area_end_pointer";
10123
10124 // void *OverflowArea;
10125 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10126 FieldNames[2] = "__overflow_area_pointer";
10127
10128 // Create fields
10129 for (unsigned i = 0; i < NumFields; ++i) {
10131 const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(),
10132 SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i],
10133 /*TInfo=*/nullptr,
10134 /*BitWidth=*/nullptr,
10135 /*Mutable=*/false, ICIS_NoInit);
10136 Field->setAccess(AS_public);
10137 VaListTagDecl->addDecl(Field);
10138 }
10139 VaListTagDecl->completeDefinition();
10140 Context->VaListTagDecl = VaListTagDecl;
10141 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10142
10143 // } __va_list_tag;
10144 TypedefDecl *VaListTagTypedefDecl =
10145 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
10146
10147 QualType VaListTagTypedefType =
10148 Context->getTypedefType(ElaboratedTypeKeyword::None,
10149 /*Qualifier=*/std::nullopt, VaListTagTypedefDecl);
10150
10151 // typedef __va_list_tag __builtin_va_list[1];
10152 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10153 QualType VaListTagArrayType = Context->getConstantArrayType(
10154 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
10155
10156 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10157}
10158
10159static TypedefDecl *
10161 // typedef struct __va_list_tag {
10162 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10163
10164 VaListTagDecl->startDefinition();
10165
10166 // int* __va_stk;
10167 // int* __va_reg;
10168 // int __va_ndx;
10169 constexpr size_t NumFields = 3;
10170 QualType FieldTypes[NumFields] = {Context->getPointerType(Context->IntTy),
10171 Context->getPointerType(Context->IntTy),
10172 Context->IntTy};
10173 const char *FieldNames[NumFields] = {"__va_stk", "__va_reg", "__va_ndx"};
10174
10175 // Create fields
10176 for (unsigned i = 0; i < NumFields; ++i) {
10179 &Context->Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
10180 /*BitWidth=*/nullptr,
10181 /*Mutable=*/false, ICIS_NoInit);
10182 Field->setAccess(AS_public);
10183 VaListTagDecl->addDecl(Field);
10184 }
10185 VaListTagDecl->completeDefinition();
10186 Context->VaListTagDecl = VaListTagDecl;
10187 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10188
10189 // } __va_list_tag;
10190 TypedefDecl *VaListTagTypedefDecl =
10191 Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
10192
10193 return VaListTagTypedefDecl;
10194}
10195
10198 switch (Kind) {
10200 return CreateCharPtrBuiltinVaListDecl(Context);
10202 return CreateVoidPtrBuiltinVaListDecl(Context);
10204 return CreateAArch64ABIBuiltinVaListDecl(Context);
10206 return CreatePowerABIBuiltinVaListDecl(Context);
10208 return CreateX86_64ABIBuiltinVaListDecl(Context);
10210 return CreateAAPCSABIBuiltinVaListDecl(Context);
10212 return CreateSystemZBuiltinVaListDecl(Context);
10214 return CreateHexagonBuiltinVaListDecl(Context);
10216 return CreateXtensaABIBuiltinVaListDecl(Context);
10217 }
10218
10219 llvm_unreachable("Unhandled __builtin_va_list type kind");
10220}
10221
10223 if (!BuiltinVaListDecl) {
10224 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
10225 assert(BuiltinVaListDecl->isImplicit());
10226 }
10227
10228 return BuiltinVaListDecl;
10229}
10230
10232 // Force the creation of VaListTagDecl by building the __builtin_va_list
10233 // declaration.
10234 if (!VaListTagDecl)
10235 (void)getBuiltinVaListDecl();
10236
10237 return VaListTagDecl;
10238}
10239
10241 if (!BuiltinMSVaListDecl)
10242 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
10243
10244 return BuiltinMSVaListDecl;
10245}
10246
10248 // Allow redecl custom type checking builtin for HLSL.
10249 if (LangOpts.HLSL && FD->getBuiltinID() != Builtin::NotBuiltin &&
10250 BuiltinInfo.hasCustomTypechecking(FD->getBuiltinID()))
10251 return true;
10252 // Allow redecl custom type checking builtin for SPIR-V.
10253 if (getTargetInfo().getTriple().isSPIROrSPIRV() &&
10254 BuiltinInfo.isTSBuiltin(FD->getBuiltinID()) &&
10255 BuiltinInfo.hasCustomTypechecking(FD->getBuiltinID()))
10256 return true;
10257 return BuiltinInfo.canBeRedeclared(FD->getBuiltinID());
10258}
10259
10261 assert(ObjCConstantStringType.isNull() &&
10262 "'NSConstantString' type already set!");
10263
10264 ObjCConstantStringType = getObjCInterfaceType(Decl);
10265}
10266
10267/// Retrieve the template name that corresponds to a non-empty
10268/// lookup.
10271 UnresolvedSetIterator End) const {
10272 unsigned size = End - Begin;
10273 assert(size > 1 && "set is not overloaded!");
10274
10275 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
10276 size * sizeof(FunctionTemplateDecl*));
10277 auto *OT = new (memory) OverloadedTemplateStorage(size);
10278
10279 NamedDecl **Storage = OT->getStorage();
10280 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
10281 NamedDecl *D = *I;
10282 assert(isa<FunctionTemplateDecl>(D) ||
10286 *Storage++ = D;
10287 }
10288
10289 return TemplateName(OT);
10290}
10291
10292/// Retrieve a template name representing an unqualified-id that has been
10293/// assumed to name a template for ADL purposes.
10295 auto *OT = new (*this) AssumedTemplateStorage(Name);
10296 return TemplateName(OT);
10297}
10298
10299/// Retrieve the template name that represents a qualified
10300/// template name such as \c std::vector.
10302 bool TemplateKeyword,
10303 TemplateName Template) const {
10304 assert(Template.getKind() == TemplateName::Template ||
10306
10307 if (Template.getAsTemplateDecl()->getKind() == Decl::TemplateTemplateParm) {
10308 assert(!Qualifier && "unexpected qualified template template parameter");
10309 assert(TemplateKeyword == false);
10310 return Template;
10311 }
10312
10313 // FIXME: Canonicalization?
10314 llvm::FoldingSetNodeID ID;
10315 QualifiedTemplateName::Profile(ID, Qualifier, TemplateKeyword, Template);
10316
10317 void *InsertPos = nullptr;
10319 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
10320 if (!QTN) {
10321 QTN = new (*this, alignof(QualifiedTemplateName))
10322 QualifiedTemplateName(Qualifier, TemplateKeyword, Template);
10323 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
10324 }
10325
10326 return TemplateName(QTN);
10327}
10328
10329/// Retrieve the template name that represents a dependent
10330/// template name such as \c MetaFun::template operator+.
10333 llvm::FoldingSetNodeID ID;
10334 S.Profile(ID);
10335
10336 void *InsertPos = nullptr;
10337 if (DependentTemplateName *QTN =
10338 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos))
10339 return TemplateName(QTN);
10340
10342 new (*this, alignof(DependentTemplateName)) DependentTemplateName(S);
10343 DependentTemplateNames.InsertNode(QTN, InsertPos);
10344 return TemplateName(QTN);
10345}
10346
10348 Decl *AssociatedDecl,
10349 unsigned Index,
10350 UnsignedOrNone PackIndex,
10351 bool Final) const {
10352 llvm::FoldingSetNodeID ID;
10353 SubstTemplateTemplateParmStorage::Profile(ID, Replacement, AssociatedDecl,
10354 Index, PackIndex, Final);
10355
10356 void *insertPos = nullptr;
10358 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
10359
10360 if (!subst) {
10361 subst = new (*this) SubstTemplateTemplateParmStorage(
10362 Replacement, AssociatedDecl, Index, PackIndex, Final);
10363 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
10364 }
10365
10366 return TemplateName(subst);
10367}
10368
10371 Decl *AssociatedDecl,
10372 unsigned Index, bool Final) const {
10373 auto &Self = const_cast<ASTContext &>(*this);
10374 llvm::FoldingSetNodeID ID;
10376 AssociatedDecl, Index, Final);
10377
10378 void *InsertPos = nullptr;
10380 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
10381
10382 if (!Subst) {
10383 Subst = new (*this) SubstTemplateTemplateParmPackStorage(
10384 ArgPack.pack_elements(), AssociatedDecl, Index, Final);
10385 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
10386 }
10387
10388 return TemplateName(Subst);
10389}
10390
10391/// Retrieve the template name that represents a template name
10392/// deduced from a specialization.
10395 DefaultArguments DefaultArgs) const {
10396 if (!DefaultArgs)
10397 return Underlying;
10398
10399 llvm::FoldingSetNodeID ID;
10400 DeducedTemplateStorage::Profile(ID, *this, Underlying, DefaultArgs);
10401
10402 void *InsertPos = nullptr;
10404 DeducedTemplates.FindNodeOrInsertPos(ID, InsertPos);
10405 if (!DTS) {
10406 void *Mem = Allocate(sizeof(DeducedTemplateStorage) +
10407 sizeof(TemplateArgument) * DefaultArgs.Args.size(),
10408 alignof(DeducedTemplateStorage));
10409 DTS = new (Mem) DeducedTemplateStorage(Underlying, DefaultArgs);
10410 DeducedTemplates.InsertNode(DTS, InsertPos);
10411 }
10412 return TemplateName(DTS);
10413}
10414
10415/// getFromTargetType - Given one of the integer types provided by
10416/// TargetInfo, produce the corresponding type. The unsigned @p Type
10417/// is actually a value of type @c TargetInfo::IntType.
10418CanQualType ASTContext::getFromTargetType(unsigned Type) const {
10419 switch (Type) {
10420 case TargetInfo::NoInt: return {};
10423 case TargetInfo::SignedShort: return ShortTy;
10425 case TargetInfo::SignedInt: return IntTy;
10427 case TargetInfo::SignedLong: return LongTy;
10431 }
10432
10433 llvm_unreachable("Unhandled TargetInfo::IntType value");
10434}
10435
10436//===----------------------------------------------------------------------===//
10437// Type Predicates.
10438//===----------------------------------------------------------------------===//
10439
10440/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
10441/// garbage collection attribute.
10442///
10444 if (getLangOpts().getGC() == LangOptions::NonGC)
10445 return Qualifiers::GCNone;
10446
10447 assert(getLangOpts().ObjC);
10448 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
10449
10450 // Default behaviour under objective-C's gc is for ObjC pointers
10451 // (or pointers to them) be treated as though they were declared
10452 // as __strong.
10453 if (GCAttrs == Qualifiers::GCNone) {
10455 return Qualifiers::Strong;
10456 else if (Ty->isPointerType())
10458 } else {
10459 // It's not valid to set GC attributes on anything that isn't a
10460 // pointer.
10461#ifndef NDEBUG
10463 while (const auto *AT = dyn_cast<ArrayType>(CT))
10464 CT = AT->getElementType();
10465 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
10466#endif
10467 }
10468 return GCAttrs;
10469}
10470
10471//===----------------------------------------------------------------------===//
10472// Type Compatibility Testing
10473//===----------------------------------------------------------------------===//
10474
10475/// areCompatVectorTypes - Return true if the two specified vector types are
10476/// compatible.
10477static bool areCompatVectorTypes(const VectorType *LHS,
10478 const VectorType *RHS) {
10479 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10480 return LHS->getElementType() == RHS->getElementType() &&
10481 LHS->getNumElements() == RHS->getNumElements();
10482}
10483
10484/// areCompatMatrixTypes - Return true if the two specified matrix types are
10485/// compatible.
10487 const ConstantMatrixType *RHS) {
10488 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10489 return LHS->getElementType() == RHS->getElementType() &&
10490 LHS->getNumRows() == RHS->getNumRows() &&
10491 LHS->getNumColumns() == RHS->getNumColumns();
10492}
10493
10495 QualType SecondVec) {
10496 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
10497 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
10498
10499 if (hasSameUnqualifiedType(FirstVec, SecondVec))
10500 return true;
10501
10502 // Treat Neon vector types and most AltiVec vector types as if they are the
10503 // equivalent GCC vector types.
10504 const auto *First = FirstVec->castAs<VectorType>();
10505 const auto *Second = SecondVec->castAs<VectorType>();
10506 if (First->getNumElements() == Second->getNumElements() &&
10507 hasSameType(First->getElementType(), Second->getElementType()) &&
10508 First->getVectorKind() != VectorKind::AltiVecPixel &&
10509 First->getVectorKind() != VectorKind::AltiVecBool &&
10512 First->getVectorKind() != VectorKind::SveFixedLengthData &&
10513 First->getVectorKind() != VectorKind::SveFixedLengthPredicate &&
10516 First->getVectorKind() != VectorKind::RVVFixedLengthData &&
10518 First->getVectorKind() != VectorKind::RVVFixedLengthMask &&
10520 First->getVectorKind() != VectorKind::RVVFixedLengthMask_1 &&
10522 First->getVectorKind() != VectorKind::RVVFixedLengthMask_2 &&
10524 First->getVectorKind() != VectorKind::RVVFixedLengthMask_4 &&
10526 return true;
10527
10528 return false;
10529}
10530
10531/// getRVVTypeSize - Return RVV vector register size.
10532static uint64_t getRVVTypeSize(ASTContext &Context, const BuiltinType *Ty) {
10533 assert(Ty->isRVVVLSBuiltinType() && "Invalid RVV Type");
10534 auto VScale = Context.getTargetInfo().getVScaleRange(
10535 Context.getLangOpts(), TargetInfo::ArmStreamingKind::NotStreaming);
10536 if (!VScale)
10537 return 0;
10538
10539 ASTContext::BuiltinVectorTypeInfo Info = Context.getBuiltinVectorTypeInfo(Ty);
10540
10541 uint64_t EltSize = Context.getTypeSize(Info.ElementType);
10542 if (Info.ElementType == Context.BoolTy)
10543 EltSize = 1;
10544
10545 uint64_t MinElts = Info.EC.getKnownMinValue();
10546 return VScale->first * MinElts * EltSize;
10547}
10548
10550 QualType SecondType) {
10551 assert(
10552 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10553 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10554 "Expected RVV builtin type and vector type!");
10555
10556 auto IsValidCast = [this](QualType FirstType, QualType SecondType) {
10557 if (const auto *BT = FirstType->getAs<BuiltinType>()) {
10558 if (const auto *VT = SecondType->getAs<VectorType>()) {
10559 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask) {
10561 return FirstType->isRVVVLSBuiltinType() &&
10562 Info.ElementType == BoolTy &&
10563 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)));
10564 }
10565 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_1) {
10567 return FirstType->isRVVVLSBuiltinType() &&
10568 Info.ElementType == BoolTy &&
10569 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT) * 8));
10570 }
10571 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_2) {
10573 return FirstType->isRVVVLSBuiltinType() &&
10574 Info.ElementType == BoolTy &&
10575 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)) * 4);
10576 }
10577 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_4) {
10579 return FirstType->isRVVVLSBuiltinType() &&
10580 Info.ElementType == BoolTy &&
10581 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)) * 2);
10582 }
10583 if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
10584 VT->getVectorKind() == VectorKind::Generic)
10585 return FirstType->isRVVVLSBuiltinType() &&
10586 getTypeSize(SecondType) == getRVVTypeSize(*this, BT) &&
10587 hasSameType(VT->getElementType(),
10588 getBuiltinVectorTypeInfo(BT).ElementType);
10589 }
10590 }
10591 return false;
10592 };
10593
10594 return IsValidCast(FirstType, SecondType) ||
10595 IsValidCast(SecondType, FirstType);
10596}
10597
10599 QualType SecondType) {
10600 assert(
10601 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10602 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10603 "Expected RVV builtin type and vector type!");
10604
10605 auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) {
10606 const auto *BT = FirstType->getAs<BuiltinType>();
10607 if (!BT)
10608 return false;
10609
10610 if (!BT->isRVVVLSBuiltinType())
10611 return false;
10612
10613 const auto *VecTy = SecondType->getAs<VectorType>();
10614 if (VecTy && VecTy->getVectorKind() == VectorKind::Generic) {
10616 getLangOpts().getLaxVectorConversions();
10617
10618 // If __riscv_v_fixed_vlen != N do not allow vector lax conversion.
10619 if (getTypeSize(SecondType) != getRVVTypeSize(*this, BT))
10620 return false;
10621
10622 // If -flax-vector-conversions=all is specified, the types are
10623 // certainly compatible.
10625 return true;
10626
10627 // If -flax-vector-conversions=integer is specified, the types are
10628 // compatible if the elements are integer types.
10630 return VecTy->getElementType().getCanonicalType()->isIntegerType() &&
10631 FirstType->getRVVEltType(*this)->isIntegerType();
10632 }
10633
10634 return false;
10635 };
10636
10637 return IsLaxCompatible(FirstType, SecondType) ||
10638 IsLaxCompatible(SecondType, FirstType);
10639}
10640
10642 while (true) {
10643 // __strong id
10644 if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) {
10645 if (Attr->getAttrKind() == attr::ObjCOwnership)
10646 return true;
10647
10648 Ty = Attr->getModifiedType();
10649
10650 // X *__strong (...)
10651 } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) {
10652 Ty = Paren->getInnerType();
10653
10654 // We do not want to look through typedefs, typeof(expr),
10655 // typeof(type), or any other way that the type is somehow
10656 // abstracted.
10657 } else {
10658 return false;
10659 }
10660 }
10661}
10662
10663//===----------------------------------------------------------------------===//
10664// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
10665//===----------------------------------------------------------------------===//
10666
10667/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
10668/// inheritance hierarchy of 'rProto'.
10669bool
10671 ObjCProtocolDecl *rProto) const {
10672 if (declaresSameEntity(lProto, rProto))
10673 return true;
10674 for (auto *PI : rProto->protocols())
10675 if (ProtocolCompatibleWithProtocol(lProto, PI))
10676 return true;
10677 return false;
10678}
10679
10680/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
10681/// Class<pr1, ...>.
10683 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) {
10684 for (auto *lhsProto : lhs->quals()) {
10685 bool match = false;
10686 for (auto *rhsProto : rhs->quals()) {
10687 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
10688 match = true;
10689 break;
10690 }
10691 }
10692 if (!match)
10693 return false;
10694 }
10695 return true;
10696}
10697
10698/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
10699/// ObjCQualifiedIDType.
10701 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs,
10702 bool compare) {
10703 // Allow id<P..> and an 'id' in all cases.
10704 if (lhs->isObjCIdType() || rhs->isObjCIdType())
10705 return true;
10706
10707 // Don't allow id<P..> to convert to Class or Class<P..> in either direction.
10708 if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() ||
10710 return false;
10711
10712 if (lhs->isObjCQualifiedIdType()) {
10713 if (rhs->qual_empty()) {
10714 // If the RHS is a unqualified interface pointer "NSString*",
10715 // make sure we check the class hierarchy.
10716 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
10717 for (auto *I : lhs->quals()) {
10718 // when comparing an id<P> on lhs with a static type on rhs,
10719 // see if static class implements all of id's protocols, directly or
10720 // through its super class and categories.
10721 if (!rhsID->ClassImplementsProtocol(I, true))
10722 return false;
10723 }
10724 }
10725 // If there are no qualifiers and no interface, we have an 'id'.
10726 return true;
10727 }
10728 // Both the right and left sides have qualifiers.
10729 for (auto *lhsProto : lhs->quals()) {
10730 bool match = false;
10731
10732 // when comparing an id<P> on lhs with a static type on rhs,
10733 // see if static class implements all of id's protocols, directly or
10734 // through its super class and categories.
10735 for (auto *rhsProto : rhs->quals()) {
10736 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
10737 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
10738 match = true;
10739 break;
10740 }
10741 }
10742 // If the RHS is a qualified interface pointer "NSString<P>*",
10743 // make sure we check the class hierarchy.
10744 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
10745 for (auto *I : lhs->quals()) {
10746 // when comparing an id<P> on lhs with a static type on rhs,
10747 // see if static class implements all of id's protocols, directly or
10748 // through its super class and categories.
10749 if (rhsID->ClassImplementsProtocol(I, true)) {
10750 match = true;
10751 break;
10752 }
10753 }
10754 }
10755 if (!match)
10756 return false;
10757 }
10758
10759 return true;
10760 }
10761
10762 assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>");
10763
10764 if (lhs->getInterfaceType()) {
10765 // If both the right and left sides have qualifiers.
10766 for (auto *lhsProto : lhs->quals()) {
10767 bool match = false;
10768
10769 // when comparing an id<P> on rhs with a static type on lhs,
10770 // see if static class implements all of id's protocols, directly or
10771 // through its super class and categories.
10772 // First, lhs protocols in the qualifier list must be found, direct
10773 // or indirect in rhs's qualifier list or it is a mismatch.
10774 for (auto *rhsProto : rhs->quals()) {
10775 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
10776 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
10777 match = true;
10778 break;
10779 }
10780 }
10781 if (!match)
10782 return false;
10783 }
10784
10785 // Static class's protocols, or its super class or category protocols
10786 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
10787 if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) {
10788 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
10789 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
10790 // This is rather dubious but matches gcc's behavior. If lhs has
10791 // no type qualifier and its class has no static protocol(s)
10792 // assume that it is mismatch.
10793 if (LHSInheritedProtocols.empty() && lhs->qual_empty())
10794 return false;
10795 for (auto *lhsProto : LHSInheritedProtocols) {
10796 bool match = false;
10797 for (auto *rhsProto : rhs->quals()) {
10798 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
10799 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
10800 match = true;
10801 break;
10802 }
10803 }
10804 if (!match)
10805 return false;
10806 }
10807 }
10808 return true;
10809 }
10810 return false;
10811}
10812
10813/// canAssignObjCInterfaces - Return true if the two interface types are
10814/// compatible for assignment from RHS to LHS. This handles validation of any
10815/// protocol qualifiers on the LHS or RHS.
10817 const ObjCObjectPointerType *RHSOPT) {
10818 const ObjCObjectType* LHS = LHSOPT->getObjectType();
10819 const ObjCObjectType* RHS = RHSOPT->getObjectType();
10820
10821 // If either type represents the built-in 'id' type, return true.
10822 if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId())
10823 return true;
10824
10825 // Function object that propagates a successful result or handles
10826 // __kindof types.
10827 auto finish = [&](bool succeeded) -> bool {
10828 if (succeeded)
10829 return true;
10830
10831 if (!RHS->isKindOfType())
10832 return false;
10833
10834 // Strip off __kindof and protocol qualifiers, then check whether
10835 // we can assign the other way.
10837 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
10838 };
10839
10840 // Casts from or to id<P> are allowed when the other side has compatible
10841 // protocols.
10842 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
10843 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false));
10844 }
10845
10846 // Verify protocol compatibility for casts from Class<P1> to Class<P2>.
10847 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
10848 return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT));
10849 }
10850
10851 // Casts from Class to Class<Foo>, or vice-versa, are allowed.
10852 if (LHS->isObjCClass() && RHS->isObjCClass()) {
10853 return true;
10854 }
10855
10856 // If we have 2 user-defined types, fall into that path.
10857 if (LHS->getInterface() && RHS->getInterface()) {
10858 return finish(canAssignObjCInterfaces(LHS, RHS));
10859 }
10860
10861 return false;
10862}
10863
10864/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
10865/// for providing type-safety for objective-c pointers used to pass/return
10866/// arguments in block literals. When passed as arguments, passing 'A*' where
10867/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
10868/// not OK. For the return type, the opposite is not OK.
10870 const ObjCObjectPointerType *LHSOPT,
10871 const ObjCObjectPointerType *RHSOPT,
10872 bool BlockReturnType) {
10873
10874 // Function object that propagates a successful result or handles
10875 // __kindof types.
10876 auto finish = [&](bool succeeded) -> bool {
10877 if (succeeded)
10878 return true;
10879
10880 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
10881 if (!Expected->isKindOfType())
10882 return false;
10883
10884 // Strip off __kindof and protocol qualifiers, then check whether
10885 // we can assign the other way.
10887 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
10888 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
10889 BlockReturnType);
10890 };
10891
10892 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
10893 return true;
10894
10895 if (LHSOPT->isObjCBuiltinType()) {
10896 return finish(RHSOPT->isObjCBuiltinType() ||
10897 RHSOPT->isObjCQualifiedIdType());
10898 }
10899
10900 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) {
10901 if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking)
10902 // Use for block parameters previous type checking for compatibility.
10903 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false) ||
10904 // Or corrected type checking as in non-compat mode.
10905 (!BlockReturnType &&
10906 ObjCQualifiedIdTypesAreCompatible(RHSOPT, LHSOPT, false)));
10907 else
10909 (BlockReturnType ? LHSOPT : RHSOPT),
10910 (BlockReturnType ? RHSOPT : LHSOPT), false));
10911 }
10912
10913 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
10914 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
10915 if (LHS && RHS) { // We have 2 user-defined types.
10916 if (LHS != RHS) {
10917 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
10918 return finish(BlockReturnType);
10919 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
10920 return finish(!BlockReturnType);
10921 }
10922 else
10923 return true;
10924 }
10925 return false;
10926}
10927
10928/// Comparison routine for Objective-C protocols to be used with
10929/// llvm::array_pod_sort.
10931 ObjCProtocolDecl * const *rhs) {
10932 return (*lhs)->getName().compare((*rhs)->getName());
10933}
10934
10935/// getIntersectionOfProtocols - This routine finds the intersection of set
10936/// of protocols inherited from two distinct objective-c pointer objects with
10937/// the given common base.
10938/// It is used to build composite qualifier list of the composite type of
10939/// the conditional expression involving two objective-c pointer objects.
10940static
10942 const ObjCInterfaceDecl *CommonBase,
10943 const ObjCObjectPointerType *LHSOPT,
10944 const ObjCObjectPointerType *RHSOPT,
10945 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
10946
10947 const ObjCObjectType* LHS = LHSOPT->getObjectType();
10948 const ObjCObjectType* RHS = RHSOPT->getObjectType();
10949 assert(LHS->getInterface() && "LHS must have an interface base");
10950 assert(RHS->getInterface() && "RHS must have an interface base");
10951
10952 // Add all of the protocols for the LHS.
10954
10955 // Start with the protocol qualifiers.
10956 for (auto *proto : LHS->quals()) {
10957 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
10958 }
10959
10960 // Also add the protocols associated with the LHS interface.
10961 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
10962
10963 // Add all of the protocols for the RHS.
10965
10966 // Start with the protocol qualifiers.
10967 for (auto *proto : RHS->quals()) {
10968 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
10969 }
10970
10971 // Also add the protocols associated with the RHS interface.
10972 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
10973
10974 // Compute the intersection of the collected protocol sets.
10975 for (auto *proto : LHSProtocolSet) {
10976 if (RHSProtocolSet.count(proto))
10977 IntersectionSet.push_back(proto);
10978 }
10979
10980 // Compute the set of protocols that is implied by either the common type or
10981 // the protocols within the intersection.
10983 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
10984
10985 // Remove any implied protocols from the list of inherited protocols.
10986 if (!ImpliedProtocols.empty()) {
10987 llvm::erase_if(IntersectionSet, [&](ObjCProtocolDecl *proto) -> bool {
10988 return ImpliedProtocols.contains(proto);
10989 });
10990 }
10991
10992 // Sort the remaining protocols by name.
10993 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
10995}
10996
10997/// Determine whether the first type is a subtype of the second.
10999 QualType rhs) {
11000 // Common case: two object pointers.
11001 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
11002 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
11003 if (lhsOPT && rhsOPT)
11004 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
11005
11006 // Two block pointers.
11007 const auto *lhsBlock = lhs->getAs<BlockPointerType>();
11008 const auto *rhsBlock = rhs->getAs<BlockPointerType>();
11009 if (lhsBlock && rhsBlock)
11010 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
11011
11012 // If either is an unqualified 'id' and the other is a block, it's
11013 // acceptable.
11014 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
11015 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
11016 return true;
11017
11018 return false;
11019}
11020
11021// Check that the given Objective-C type argument lists are equivalent.
11023 const ObjCInterfaceDecl *iface,
11024 ArrayRef<QualType> lhsArgs,
11025 ArrayRef<QualType> rhsArgs,
11026 bool stripKindOf) {
11027 if (lhsArgs.size() != rhsArgs.size())
11028 return false;
11029
11030 ObjCTypeParamList *typeParams = iface->getTypeParamList();
11031 if (!typeParams)
11032 return false;
11033
11034 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
11035 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
11036 continue;
11037
11038 switch (typeParams->begin()[i]->getVariance()) {
11040 if (!stripKindOf ||
11041 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
11042 rhsArgs[i].stripObjCKindOfType(ctx))) {
11043 return false;
11044 }
11045 break;
11046
11048 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
11049 return false;
11050 break;
11051
11053 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
11054 return false;
11055 break;
11056 }
11057 }
11058
11059 return true;
11060}
11061
11063 const ObjCObjectPointerType *Lptr,
11064 const ObjCObjectPointerType *Rptr) {
11065 const ObjCObjectType *LHS = Lptr->getObjectType();
11066 const ObjCObjectType *RHS = Rptr->getObjectType();
11067 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
11068 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
11069
11070 if (!LDecl || !RDecl)
11071 return {};
11072
11073 // When either LHS or RHS is a kindof type, we should return a kindof type.
11074 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
11075 // kindof(A).
11076 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
11077
11078 // Follow the left-hand side up the class hierarchy until we either hit a
11079 // root or find the RHS. Record the ancestors in case we don't find it.
11080 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
11081 LHSAncestors;
11082 while (true) {
11083 // Record this ancestor. We'll need this if the common type isn't in the
11084 // path from the LHS to the root.
11085 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
11086
11087 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
11088 // Get the type arguments.
11089 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
11090 bool anyChanges = false;
11091 if (LHS->isSpecialized() && RHS->isSpecialized()) {
11092 // Both have type arguments, compare them.
11093 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
11094 LHS->getTypeArgs(), RHS->getTypeArgs(),
11095 /*stripKindOf=*/true))
11096 return {};
11097 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
11098 // If only one has type arguments, the result will not have type
11099 // arguments.
11100 LHSTypeArgs = {};
11101 anyChanges = true;
11102 }
11103
11104 // Compute the intersection of protocols.
11106 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
11107 Protocols);
11108 if (!Protocols.empty())
11109 anyChanges = true;
11110
11111 // If anything in the LHS will have changed, build a new result type.
11112 // If we need to return a kindof type but LHS is not a kindof type, we
11113 // build a new result type.
11114 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
11115 QualType Result = getObjCInterfaceType(LHS->getInterface());
11116 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
11117 anyKindOf || LHS->isKindOfType());
11119 }
11120
11121 return getObjCObjectPointerType(QualType(LHS, 0));
11122 }
11123
11124 // Find the superclass.
11125 QualType LHSSuperType = LHS->getSuperClassType();
11126 if (LHSSuperType.isNull())
11127 break;
11128
11129 LHS = LHSSuperType->castAs<ObjCObjectType>();
11130 }
11131
11132 // We didn't find anything by following the LHS to its root; now check
11133 // the RHS against the cached set of ancestors.
11134 while (true) {
11135 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
11136 if (KnownLHS != LHSAncestors.end()) {
11137 LHS = KnownLHS->second;
11138
11139 // Get the type arguments.
11140 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
11141 bool anyChanges = false;
11142 if (LHS->isSpecialized() && RHS->isSpecialized()) {
11143 // Both have type arguments, compare them.
11144 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
11145 LHS->getTypeArgs(), RHS->getTypeArgs(),
11146 /*stripKindOf=*/true))
11147 return {};
11148 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
11149 // If only one has type arguments, the result will not have type
11150 // arguments.
11151 RHSTypeArgs = {};
11152 anyChanges = true;
11153 }
11154
11155 // Compute the intersection of protocols.
11157 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
11158 Protocols);
11159 if (!Protocols.empty())
11160 anyChanges = true;
11161
11162 // If we need to return a kindof type but RHS is not a kindof type, we
11163 // build a new result type.
11164 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
11165 QualType Result = getObjCInterfaceType(RHS->getInterface());
11166 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
11167 anyKindOf || RHS->isKindOfType());
11169 }
11170
11171 return getObjCObjectPointerType(QualType(RHS, 0));
11172 }
11173
11174 // Find the superclass of the RHS.
11175 QualType RHSSuperType = RHS->getSuperClassType();
11176 if (RHSSuperType.isNull())
11177 break;
11178
11179 RHS = RHSSuperType->castAs<ObjCObjectType>();
11180 }
11181
11182 return {};
11183}
11184
11186 const ObjCObjectType *RHS) {
11187 assert(LHS->getInterface() && "LHS is not an interface type");
11188 assert(RHS->getInterface() && "RHS is not an interface type");
11189
11190 // Verify that the base decls are compatible: the RHS must be a subclass of
11191 // the LHS.
11192 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
11193 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
11194 if (!IsSuperClass)
11195 return false;
11196
11197 // If the LHS has protocol qualifiers, determine whether all of them are
11198 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
11199 // LHS).
11200 if (LHS->getNumProtocols() > 0) {
11201 // OK if conversion of LHS to SuperClass results in narrowing of types
11202 // ; i.e., SuperClass may implement at least one of the protocols
11203 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
11204 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
11205 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
11206 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
11207 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
11208 // qualifiers.
11209 for (auto *RHSPI : RHS->quals())
11210 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
11211 // If there is no protocols associated with RHS, it is not a match.
11212 if (SuperClassInheritedProtocols.empty())
11213 return false;
11214
11215 for (const auto *LHSProto : LHS->quals()) {
11216 bool SuperImplementsProtocol = false;
11217 for (auto *SuperClassProto : SuperClassInheritedProtocols)
11218 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
11219 SuperImplementsProtocol = true;
11220 break;
11221 }
11222 if (!SuperImplementsProtocol)
11223 return false;
11224 }
11225 }
11226
11227 // If the LHS is specialized, we may need to check type arguments.
11228 if (LHS->isSpecialized()) {
11229 // Follow the superclass chain until we've matched the LHS class in the
11230 // hierarchy. This substitutes type arguments through.
11231 const ObjCObjectType *RHSSuper = RHS;
11232 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
11233 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
11234
11235 // If the RHS is specializd, compare type arguments.
11236 if (RHSSuper->isSpecialized() &&
11237 !sameObjCTypeArgs(*this, LHS->getInterface(),
11238 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
11239 /*stripKindOf=*/true)) {
11240 return false;
11241 }
11242 }
11243
11244 return true;
11245}
11246
11248 // get the "pointed to" types
11249 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
11250 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
11251
11252 if (!LHSOPT || !RHSOPT)
11253 return false;
11254
11255 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
11256 canAssignObjCInterfaces(RHSOPT, LHSOPT);
11257}
11258
11261 getObjCObjectPointerType(To)->castAs<ObjCObjectPointerType>(),
11262 getObjCObjectPointerType(From)->castAs<ObjCObjectPointerType>());
11263}
11264
11265/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
11266/// both shall have the identically qualified version of a compatible type.
11267/// C99 6.2.7p1: Two types have compatible types if their types are the
11268/// same. See 6.7.[2,3,5] for additional rules.
11270 bool CompareUnqualified) {
11271 if (getLangOpts().CPlusPlus)
11272 return hasSameType(LHS, RHS);
11273
11274 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
11275}
11276
11278 return typesAreCompatible(LHS, RHS);
11279}
11280
11282 return !mergeTypes(LHS, RHS, true).isNull();
11283}
11284
11285/// mergeTransparentUnionType - if T is a transparent union type and a member
11286/// of T is compatible with SubType, return the merged type, else return
11287/// QualType()
11289 bool OfBlockPointer,
11290 bool Unqualified) {
11291 if (const RecordType *UT = T->getAsUnionType()) {
11292 RecordDecl *UD = UT->getDecl()->getMostRecentDecl();
11293 if (UD->hasAttr<TransparentUnionAttr>()) {
11294 for (const auto *I : UD->fields()) {
11295 QualType ET = I->getType().getUnqualifiedType();
11296 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
11297 if (!MT.isNull())
11298 return MT;
11299 }
11300 }
11301 }
11302
11303 return {};
11304}
11305
11306/// mergeFunctionParameterTypes - merge two types which appear as function
11307/// parameter types
11309 bool OfBlockPointer,
11310 bool Unqualified) {
11311 // GNU extension: two types are compatible if they appear as a function
11312 // argument, one of the types is a transparent union type and the other
11313 // type is compatible with a union member
11314 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
11315 Unqualified);
11316 if (!lmerge.isNull())
11317 return lmerge;
11318
11319 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
11320 Unqualified);
11321 if (!rmerge.isNull())
11322 return rmerge;
11323
11324 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
11325}
11326
11328 bool OfBlockPointer, bool Unqualified,
11329 bool AllowCXX,
11330 bool IsConditionalOperator) {
11331 const auto *lbase = lhs->castAs<FunctionType>();
11332 const auto *rbase = rhs->castAs<FunctionType>();
11333 const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
11334 const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
11335 bool allLTypes = true;
11336 bool allRTypes = true;
11337
11338 // Check return type
11339 QualType retType;
11340 if (OfBlockPointer) {
11341 QualType RHS = rbase->getReturnType();
11342 QualType LHS = lbase->getReturnType();
11343 bool UnqualifiedResult = Unqualified;
11344 if (!UnqualifiedResult)
11345 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
11346 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
11347 }
11348 else
11349 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
11350 Unqualified);
11351 if (retType.isNull())
11352 return {};
11353
11354 if (Unqualified)
11355 retType = retType.getUnqualifiedType();
11356
11357 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
11358 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
11359 if (Unqualified) {
11360 LRetType = LRetType.getUnqualifiedType();
11361 RRetType = RRetType.getUnqualifiedType();
11362 }
11363
11364 if (getCanonicalType(retType) != LRetType)
11365 allLTypes = false;
11366 if (getCanonicalType(retType) != RRetType)
11367 allRTypes = false;
11368
11369 // FIXME: double check this
11370 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
11371 // rbase->getRegParmAttr() != 0 &&
11372 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
11373 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
11374 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
11375
11376 // Compatible functions must have compatible calling conventions
11377 if (lbaseInfo.getCC() != rbaseInfo.getCC())
11378 return {};
11379
11380 // Regparm is part of the calling convention.
11381 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
11382 return {};
11383 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
11384 return {};
11385
11386 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
11387 return {};
11388 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
11389 return {};
11390 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
11391 return {};
11392
11393 // When merging declarations, it's common for supplemental information like
11394 // attributes to only be present in one of the declarations, and we generally
11395 // want type merging to preserve the union of information. So a merged
11396 // function type should be noreturn if it was noreturn in *either* operand
11397 // type.
11398 //
11399 // But for the conditional operator, this is backwards. The result of the
11400 // operator could be either operand, and its type should conservatively
11401 // reflect that. So a function type in a composite type is noreturn only
11402 // if it's noreturn in *both* operand types.
11403 //
11404 // Arguably, noreturn is a kind of subtype, and the conditional operator
11405 // ought to produce the most specific common supertype of its operand types.
11406 // That would differ from this rule in contravariant positions. However,
11407 // neither C nor C++ generally uses this kind of subtype reasoning. Also,
11408 // as a practical matter, it would only affect C code that does abstraction of
11409 // higher-order functions (taking noreturn callbacks!), which is uncommon to
11410 // say the least. So we use the simpler rule.
11411 bool NoReturn = IsConditionalOperator
11412 ? lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn()
11413 : lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
11414 if (lbaseInfo.getNoReturn() != NoReturn)
11415 allLTypes = false;
11416 if (rbaseInfo.getNoReturn() != NoReturn)
11417 allRTypes = false;
11418
11419 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
11420
11421 std::optional<FunctionEffectSet> MergedFX;
11422
11423 if (lproto && rproto) { // two C99 style function prototypes
11424 assert((AllowCXX ||
11425 (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) &&
11426 "C++ shouldn't be here");
11427 // Compatible functions must have the same number of parameters
11428 if (lproto->getNumParams() != rproto->getNumParams())
11429 return {};
11430
11431 // Variadic and non-variadic functions aren't compatible
11432 if (lproto->isVariadic() != rproto->isVariadic())
11433 return {};
11434
11435 if (lproto->getMethodQuals() != rproto->getMethodQuals())
11436 return {};
11437
11438 // Function protos with different 'cfi_salt' values aren't compatible.
11439 if (lproto->getExtraAttributeInfo().CFISalt !=
11440 rproto->getExtraAttributeInfo().CFISalt)
11441 return {};
11442
11443 // Function effects are handled similarly to noreturn, see above.
11444 FunctionEffectsRef LHSFX = lproto->getFunctionEffects();
11445 FunctionEffectsRef RHSFX = rproto->getFunctionEffects();
11446 if (LHSFX != RHSFX) {
11447 if (IsConditionalOperator)
11448 MergedFX = FunctionEffectSet::getIntersection(LHSFX, RHSFX);
11449 else {
11451 MergedFX = FunctionEffectSet::getUnion(LHSFX, RHSFX, Errs);
11452 // Here we're discarding a possible error due to conflicts in the effect
11453 // sets. But we're not in a context where we can report it. The
11454 // operation does however guarantee maintenance of invariants.
11455 }
11456 if (*MergedFX != LHSFX)
11457 allLTypes = false;
11458 if (*MergedFX != RHSFX)
11459 allRTypes = false;
11460 }
11461
11463 bool canUseLeft, canUseRight;
11464 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
11465 newParamInfos))
11466 return {};
11467
11468 if (!canUseLeft)
11469 allLTypes = false;
11470 if (!canUseRight)
11471 allRTypes = false;
11472
11473 // Check parameter type compatibility
11475 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
11476 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
11477 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
11479 lParamType, rParamType, OfBlockPointer, Unqualified);
11480 if (paramType.isNull())
11481 return {};
11482
11483 if (Unqualified)
11484 paramType = paramType.getUnqualifiedType();
11485
11486 types.push_back(paramType);
11487 if (Unqualified) {
11488 lParamType = lParamType.getUnqualifiedType();
11489 rParamType = rParamType.getUnqualifiedType();
11490 }
11491
11492 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
11493 allLTypes = false;
11494 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
11495 allRTypes = false;
11496 }
11497
11498 if (allLTypes) return lhs;
11499 if (allRTypes) return rhs;
11500
11501 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
11502 EPI.ExtInfo = einfo;
11503 EPI.ExtParameterInfos =
11504 newParamInfos.empty() ? nullptr : newParamInfos.data();
11505 if (MergedFX)
11506 EPI.FunctionEffects = *MergedFX;
11507 return getFunctionType(retType, types, EPI);
11508 }
11509
11510 if (lproto) allRTypes = false;
11511 if (rproto) allLTypes = false;
11512
11513 const FunctionProtoType *proto = lproto ? lproto : rproto;
11514 if (proto) {
11515 assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here");
11516 if (proto->isVariadic())
11517 return {};
11518 // Check that the types are compatible with the types that
11519 // would result from default argument promotions (C99 6.7.5.3p15).
11520 // The only types actually affected are promotable integer
11521 // types and floats, which would be passed as a different
11522 // type depending on whether the prototype is visible.
11523 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
11524 QualType paramTy = proto->getParamType(i);
11525
11526 // Look at the converted type of enum types, since that is the type used
11527 // to pass enum values.
11528 if (const auto *ED = paramTy->getAsEnumDecl()) {
11529 paramTy = ED->getIntegerType();
11530 if (paramTy.isNull())
11531 return {};
11532 }
11533
11534 if (isPromotableIntegerType(paramTy) ||
11535 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
11536 return {};
11537 }
11538
11539 if (allLTypes) return lhs;
11540 if (allRTypes) return rhs;
11541
11543 EPI.ExtInfo = einfo;
11544 if (MergedFX)
11545 EPI.FunctionEffects = *MergedFX;
11546 return getFunctionType(retType, proto->getParamTypes(), EPI);
11547 }
11548
11549 if (allLTypes) return lhs;
11550 if (allRTypes) return rhs;
11551 return getFunctionNoProtoType(retType, einfo);
11552}
11553
11554/// Given that we have an enum type and a non-enum type, try to merge them.
11555static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
11556 QualType other, bool isBlockReturnType) {
11557 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
11558 // a signed integer type, or an unsigned integer type.
11559 // Compatibility is based on the underlying type, not the promotion
11560 // type.
11561 QualType underlyingType =
11562 ET->getDecl()->getDefinitionOrSelf()->getIntegerType();
11563 if (underlyingType.isNull())
11564 return {};
11565 if (Context.hasSameType(underlyingType, other))
11566 return other;
11567
11568 // In block return types, we're more permissive and accept any
11569 // integral type of the same size.
11570 if (isBlockReturnType && other->isIntegerType() &&
11571 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
11572 return other;
11573
11574 return {};
11575}
11576
11578 // C17 and earlier and C++ disallow two tag definitions within the same TU
11579 // from being compatible.
11580 if (LangOpts.CPlusPlus || !LangOpts.C23)
11581 return {};
11582
11583 // Nameless tags are comparable only within outer definitions. At the top
11584 // level they are not comparable.
11585 const TagDecl *LTagD = LHS->castAsTagDecl(), *RTagD = RHS->castAsTagDecl();
11586 if (!LTagD->getIdentifier() || !RTagD->getIdentifier())
11587 return {};
11588
11589 // C23, on the other hand, requires the members to be "the same enough", so
11590 // we use a structural equivalence check.
11593 getLangOpts(), *this, *this, NonEquivalentDecls,
11594 StructuralEquivalenceKind::Default, /*StrictTypeSpelling=*/false,
11595 /*Complain=*/false, /*ErrorOnTagTypeMismatch=*/true);
11596 return Ctx.IsEquivalent(LHS, RHS) ? LHS : QualType{};
11597}
11598
11599QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
11600 bool Unqualified, bool BlockReturnType,
11601 bool IsConditionalOperator) {
11602 // For C++ we will not reach this code with reference types (see below),
11603 // for OpenMP variant call overloading we might.
11604 //
11605 // C++ [expr]: If an expression initially has the type "reference to T", the
11606 // type is adjusted to "T" prior to any further analysis, the expression
11607 // designates the object or function denoted by the reference, and the
11608 // expression is an lvalue unless the reference is an rvalue reference and
11609 // the expression is a function call (possibly inside parentheses).
11610 auto *LHSRefTy = LHS->getAs<ReferenceType>();
11611 auto *RHSRefTy = RHS->getAs<ReferenceType>();
11612 if (LangOpts.OpenMP && LHSRefTy && RHSRefTy &&
11613 LHS->getTypeClass() == RHS->getTypeClass())
11614 return mergeTypes(LHSRefTy->getPointeeType(), RHSRefTy->getPointeeType(),
11615 OfBlockPointer, Unqualified, BlockReturnType);
11616 if (LHSRefTy || RHSRefTy)
11617 return {};
11618
11619 if (Unqualified) {
11620 LHS = LHS.getUnqualifiedType();
11621 RHS = RHS.getUnqualifiedType();
11622 }
11623
11624 QualType LHSCan = getCanonicalType(LHS),
11625 RHSCan = getCanonicalType(RHS);
11626
11627 // If two types are identical, they are compatible.
11628 if (LHSCan == RHSCan)
11629 return LHS;
11630
11631 // If the qualifiers are different, the types aren't compatible... mostly.
11632 Qualifiers LQuals = LHSCan.getLocalQualifiers();
11633 Qualifiers RQuals = RHSCan.getLocalQualifiers();
11634 if (LQuals != RQuals) {
11635 // If any of these qualifiers are different, we have a type
11636 // mismatch.
11637 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
11638 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
11639 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
11640 !LQuals.getPointerAuth().isEquivalent(RQuals.getPointerAuth()) ||
11641 LQuals.hasUnaligned() != RQuals.hasUnaligned())
11642 return {};
11643
11644 // Exactly one GC qualifier difference is allowed: __strong is
11645 // okay if the other type has no GC qualifier but is an Objective
11646 // C object pointer (i.e. implicitly strong by default). We fix
11647 // this by pretending that the unqualified type was actually
11648 // qualified __strong.
11649 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
11650 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
11651 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
11652
11653 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
11654 return {};
11655
11656 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
11658 }
11659 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
11661 }
11662 return {};
11663 }
11664
11665 // Okay, qualifiers are equal.
11666
11667 Type::TypeClass LHSClass = LHSCan->getTypeClass();
11668 Type::TypeClass RHSClass = RHSCan->getTypeClass();
11669
11670 // We want to consider the two function types to be the same for these
11671 // comparisons, just force one to the other.
11672 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
11673 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
11674
11675 // Same as above for arrays
11676 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
11677 LHSClass = Type::ConstantArray;
11678 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
11679 RHSClass = Type::ConstantArray;
11680
11681 // ObjCInterfaces are just specialized ObjCObjects.
11682 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
11683 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
11684
11685 // Canonicalize ExtVector -> Vector.
11686 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
11687 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
11688
11689 // If the canonical type classes don't match.
11690 if (LHSClass != RHSClass) {
11691 // Note that we only have special rules for turning block enum
11692 // returns into block int returns, not vice-versa.
11693 if (const auto *ETy = LHS->getAsCanonical<EnumType>()) {
11694 return mergeEnumWithInteger(*this, ETy, RHS, false);
11695 }
11696 if (const EnumType *ETy = RHS->getAsCanonical<EnumType>()) {
11697 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
11698 }
11699 // allow block pointer type to match an 'id' type.
11700 if (OfBlockPointer && !BlockReturnType) {
11701 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
11702 return LHS;
11703 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
11704 return RHS;
11705 }
11706 // Allow __auto_type to match anything; it merges to the type with more
11707 // information.
11708 if (const auto *AT = LHS->getAs<AutoType>()) {
11709 if (!AT->isDeduced() && AT->isGNUAutoType())
11710 return RHS;
11711 }
11712 if (const auto *AT = RHS->getAs<AutoType>()) {
11713 if (!AT->isDeduced() && AT->isGNUAutoType())
11714 return LHS;
11715 }
11716 return {};
11717 }
11718
11719 // The canonical type classes match.
11720 switch (LHSClass) {
11721#define TYPE(Class, Base)
11722#define ABSTRACT_TYPE(Class, Base)
11723#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
11724#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
11725#define DEPENDENT_TYPE(Class, Base) case Type::Class:
11726#include "clang/AST/TypeNodes.inc"
11727 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
11728
11729 case Type::Auto:
11730 case Type::DeducedTemplateSpecialization:
11731 case Type::LValueReference:
11732 case Type::RValueReference:
11733 case Type::MemberPointer:
11734 llvm_unreachable("C++ should never be in mergeTypes");
11735
11736 case Type::ObjCInterface:
11737 case Type::IncompleteArray:
11738 case Type::VariableArray:
11739 case Type::FunctionProto:
11740 case Type::ExtVector:
11741 llvm_unreachable("Types are eliminated above");
11742
11743 case Type::Pointer:
11744 {
11745 // Merge two pointer types, while trying to preserve typedef info
11746 QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType();
11747 QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType();
11748 if (Unqualified) {
11749 LHSPointee = LHSPointee.getUnqualifiedType();
11750 RHSPointee = RHSPointee.getUnqualifiedType();
11751 }
11752 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
11753 Unqualified);
11754 if (ResultType.isNull())
11755 return {};
11756 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
11757 return LHS;
11758 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
11759 return RHS;
11760 return getPointerType(ResultType);
11761 }
11762 case Type::BlockPointer:
11763 {
11764 // Merge two block pointer types, while trying to preserve typedef info
11765 QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType();
11766 QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType();
11767 if (Unqualified) {
11768 LHSPointee = LHSPointee.getUnqualifiedType();
11769 RHSPointee = RHSPointee.getUnqualifiedType();
11770 }
11771 if (getLangOpts().OpenCL) {
11772 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
11773 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
11774 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
11775 // 6.12.5) thus the following check is asymmetric.
11776 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual, *this))
11777 return {};
11778 LHSPteeQual.removeAddressSpace();
11779 RHSPteeQual.removeAddressSpace();
11780 LHSPointee =
11781 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
11782 RHSPointee =
11783 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
11784 }
11785 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
11786 Unqualified);
11787 if (ResultType.isNull())
11788 return {};
11789 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
11790 return LHS;
11791 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
11792 return RHS;
11793 return getBlockPointerType(ResultType);
11794 }
11795 case Type::Atomic:
11796 {
11797 // Merge two pointer types, while trying to preserve typedef info
11798 QualType LHSValue = LHS->castAs<AtomicType>()->getValueType();
11799 QualType RHSValue = RHS->castAs<AtomicType>()->getValueType();
11800 if (Unqualified) {
11801 LHSValue = LHSValue.getUnqualifiedType();
11802 RHSValue = RHSValue.getUnqualifiedType();
11803 }
11804 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
11805 Unqualified);
11806 if (ResultType.isNull())
11807 return {};
11808 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
11809 return LHS;
11810 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
11811 return RHS;
11812 return getAtomicType(ResultType);
11813 }
11814 case Type::ConstantArray:
11815 {
11816 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
11817 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
11818 if (LCAT && RCAT && RCAT->getZExtSize() != LCAT->getZExtSize())
11819 return {};
11820
11821 QualType LHSElem = getAsArrayType(LHS)->getElementType();
11822 QualType RHSElem = getAsArrayType(RHS)->getElementType();
11823 if (Unqualified) {
11824 LHSElem = LHSElem.getUnqualifiedType();
11825 RHSElem = RHSElem.getUnqualifiedType();
11826 }
11827
11828 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
11829 if (ResultType.isNull())
11830 return {};
11831
11832 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
11833 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
11834
11835 // If either side is a variable array, and both are complete, check whether
11836 // the current dimension is definite.
11837 if (LVAT || RVAT) {
11838 auto SizeFetch = [this](const VariableArrayType* VAT,
11839 const ConstantArrayType* CAT)
11840 -> std::pair<bool,llvm::APInt> {
11841 if (VAT) {
11842 std::optional<llvm::APSInt> TheInt;
11843 Expr *E = VAT->getSizeExpr();
11844 if (E && (TheInt = E->getIntegerConstantExpr(*this)))
11845 return std::make_pair(true, *TheInt);
11846 return std::make_pair(false, llvm::APSInt());
11847 }
11848 if (CAT)
11849 return std::make_pair(true, CAT->getSize());
11850 return std::make_pair(false, llvm::APInt());
11851 };
11852
11853 bool HaveLSize, HaveRSize;
11854 llvm::APInt LSize, RSize;
11855 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
11856 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
11857 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
11858 return {}; // Definite, but unequal, array dimension
11859 }
11860
11861 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
11862 return LHS;
11863 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
11864 return RHS;
11865 if (LCAT)
11866 return getConstantArrayType(ResultType, LCAT->getSize(),
11867 LCAT->getSizeExpr(), ArraySizeModifier(), 0);
11868 if (RCAT)
11869 return getConstantArrayType(ResultType, RCAT->getSize(),
11870 RCAT->getSizeExpr(), ArraySizeModifier(), 0);
11871 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
11872 return LHS;
11873 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
11874 return RHS;
11875 if (LVAT) {
11876 // FIXME: This isn't correct! But tricky to implement because
11877 // the array's size has to be the size of LHS, but the type
11878 // has to be different.
11879 return LHS;
11880 }
11881 if (RVAT) {
11882 // FIXME: This isn't correct! But tricky to implement because
11883 // the array's size has to be the size of RHS, but the type
11884 // has to be different.
11885 return RHS;
11886 }
11887 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
11888 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
11889 return getIncompleteArrayType(ResultType, ArraySizeModifier(), 0);
11890 }
11891 case Type::FunctionNoProto:
11892 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified,
11893 /*AllowCXX=*/false, IsConditionalOperator);
11894 case Type::Record:
11895 case Type::Enum:
11896 return mergeTagDefinitions(LHS, RHS);
11897 case Type::Builtin:
11898 // Only exactly equal builtin types are compatible, which is tested above.
11899 return {};
11900 case Type::Complex:
11901 // Distinct complex types are incompatible.
11902 return {};
11903 case Type::Vector:
11904 // FIXME: The merged type should be an ExtVector!
11905 if (areCompatVectorTypes(LHSCan->castAs<VectorType>(),
11906 RHSCan->castAs<VectorType>()))
11907 return LHS;
11908 return {};
11909 case Type::ConstantMatrix:
11911 RHSCan->castAs<ConstantMatrixType>()))
11912 return LHS;
11913 return {};
11914 case Type::ObjCObject: {
11915 // Check if the types are assignment compatible.
11916 // FIXME: This should be type compatibility, e.g. whether
11917 // "LHS x; RHS x;" at global scope is legal.
11919 RHS->castAs<ObjCObjectType>()))
11920 return LHS;
11921 return {};
11922 }
11923 case Type::ObjCObjectPointer:
11924 if (OfBlockPointer) {
11927 RHS->castAs<ObjCObjectPointerType>(), BlockReturnType))
11928 return LHS;
11929 return {};
11930 }
11933 return LHS;
11934 return {};
11935 case Type::Pipe:
11936 assert(LHS != RHS &&
11937 "Equivalent pipe types should have already been handled!");
11938 return {};
11939 case Type::ArrayParameter:
11940 assert(LHS != RHS &&
11941 "Equivalent ArrayParameter types should have already been handled!");
11942 return {};
11943 case Type::BitInt: {
11944 // Merge two bit-precise int types, while trying to preserve typedef info.
11945 bool LHSUnsigned = LHS->castAs<BitIntType>()->isUnsigned();
11946 bool RHSUnsigned = RHS->castAs<BitIntType>()->isUnsigned();
11947 unsigned LHSBits = LHS->castAs<BitIntType>()->getNumBits();
11948 unsigned RHSBits = RHS->castAs<BitIntType>()->getNumBits();
11949
11950 // Like unsigned/int, shouldn't have a type if they don't match.
11951 if (LHSUnsigned != RHSUnsigned)
11952 return {};
11953
11954 if (LHSBits != RHSBits)
11955 return {};
11956 return LHS;
11957 }
11958 case Type::HLSLAttributedResource: {
11959 const HLSLAttributedResourceType *LHSTy =
11960 LHS->castAs<HLSLAttributedResourceType>();
11961 const HLSLAttributedResourceType *RHSTy =
11962 RHS->castAs<HLSLAttributedResourceType>();
11963 assert(LHSTy->getWrappedType() == RHSTy->getWrappedType() &&
11964 LHSTy->getWrappedType()->isHLSLResourceType() &&
11965 "HLSLAttributedResourceType should always wrap __hlsl_resource_t");
11966
11967 if (LHSTy->getAttrs() == RHSTy->getAttrs() &&
11968 LHSTy->getContainedType() == RHSTy->getContainedType())
11969 return LHS;
11970 return {};
11971 }
11972 case Type::HLSLInlineSpirv:
11973 const HLSLInlineSpirvType *LHSTy = LHS->castAs<HLSLInlineSpirvType>();
11974 const HLSLInlineSpirvType *RHSTy = RHS->castAs<HLSLInlineSpirvType>();
11975
11976 if (LHSTy->getOpcode() == RHSTy->getOpcode() &&
11977 LHSTy->getSize() == RHSTy->getSize() &&
11978 LHSTy->getAlignment() == RHSTy->getAlignment()) {
11979 for (size_t I = 0; I < LHSTy->getOperands().size(); I++)
11980 if (LHSTy->getOperands()[I] != RHSTy->getOperands()[I])
11981 return {};
11982
11983 return LHS;
11984 }
11985 return {};
11986 }
11987
11988 llvm_unreachable("Invalid Type::Class!");
11989}
11990
11992 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
11993 bool &CanUseFirst, bool &CanUseSecond,
11995 assert(NewParamInfos.empty() && "param info list not empty");
11996 CanUseFirst = CanUseSecond = true;
11997 bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
11998 bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
11999
12000 // Fast path: if the first type doesn't have ext parameter infos,
12001 // we match if and only if the second type also doesn't have them.
12002 if (!FirstHasInfo && !SecondHasInfo)
12003 return true;
12004
12005 bool NeedParamInfo = false;
12006 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
12007 : SecondFnType->getExtParameterInfos().size();
12008
12009 for (size_t I = 0; I < E; ++I) {
12010 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
12011 if (FirstHasInfo)
12012 FirstParam = FirstFnType->getExtParameterInfo(I);
12013 if (SecondHasInfo)
12014 SecondParam = SecondFnType->getExtParameterInfo(I);
12015
12016 // Cannot merge unless everything except the noescape flag matches.
12017 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
12018 return false;
12019
12020 bool FirstNoEscape = FirstParam.isNoEscape();
12021 bool SecondNoEscape = SecondParam.isNoEscape();
12022 bool IsNoEscape = FirstNoEscape && SecondNoEscape;
12023 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
12024 if (NewParamInfos.back().getOpaqueValue())
12025 NeedParamInfo = true;
12026 if (FirstNoEscape != IsNoEscape)
12027 CanUseFirst = false;
12028 if (SecondNoEscape != IsNoEscape)
12029 CanUseSecond = false;
12030 }
12031
12032 if (!NeedParamInfo)
12033 NewParamInfos.clear();
12034
12035 return true;
12036}
12037
12039 if (auto It = ObjCLayouts.find(D); It != ObjCLayouts.end()) {
12040 It->second = nullptr;
12041 for (auto *SubClass : ObjCSubClasses[D])
12042 ResetObjCLayout(SubClass);
12043 }
12044}
12045
12046/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
12047/// 'RHS' attributes and returns the merged version; including for function
12048/// return types.
12050 QualType LHSCan = getCanonicalType(LHS),
12051 RHSCan = getCanonicalType(RHS);
12052 // If two types are identical, they are compatible.
12053 if (LHSCan == RHSCan)
12054 return LHS;
12055 if (RHSCan->isFunctionType()) {
12056 if (!LHSCan->isFunctionType())
12057 return {};
12058 QualType OldReturnType =
12059 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
12060 QualType NewReturnType =
12061 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
12062 QualType ResReturnType =
12063 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
12064 if (ResReturnType.isNull())
12065 return {};
12066 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
12067 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
12068 // In either case, use OldReturnType to build the new function type.
12069 const auto *F = LHS->castAs<FunctionType>();
12070 if (const auto *FPT = cast<FunctionProtoType>(F)) {
12071 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12072 EPI.ExtInfo = getFunctionExtInfo(LHS);
12073 QualType ResultType =
12074 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
12075 return ResultType;
12076 }
12077 }
12078 return {};
12079 }
12080
12081 // If the qualifiers are different, the types can still be merged.
12082 Qualifiers LQuals = LHSCan.getLocalQualifiers();
12083 Qualifiers RQuals = RHSCan.getLocalQualifiers();
12084 if (LQuals != RQuals) {
12085 // If any of these qualifiers are different, we have a type mismatch.
12086 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
12087 LQuals.getAddressSpace() != RQuals.getAddressSpace())
12088 return {};
12089
12090 // Exactly one GC qualifier difference is allowed: __strong is
12091 // okay if the other type has no GC qualifier but is an Objective
12092 // C object pointer (i.e. implicitly strong by default). We fix
12093 // this by pretending that the unqualified type was actually
12094 // qualified __strong.
12095 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
12096 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
12097 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
12098
12099 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
12100 return {};
12101
12102 if (GC_L == Qualifiers::Strong)
12103 return LHS;
12104 if (GC_R == Qualifiers::Strong)
12105 return RHS;
12106 return {};
12107 }
12108
12109 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
12110 QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType();
12111 QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType();
12112 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
12113 if (ResQT == LHSBaseQT)
12114 return LHS;
12115 if (ResQT == RHSBaseQT)
12116 return RHS;
12117 }
12118 return {};
12119}
12120
12121//===----------------------------------------------------------------------===//
12122// Integer Predicates
12123//===----------------------------------------------------------------------===//
12124
12126 if (const auto *ED = T->getAsEnumDecl())
12127 T = ED->getIntegerType();
12128 if (T->isBooleanType())
12129 return 1;
12130 if (const auto *EIT = T->getAs<BitIntType>())
12131 return EIT->getNumBits();
12132 // For builtin types, just use the standard type sizing method
12133 return (unsigned)getTypeSize(T);
12134}
12135
12137 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
12138 T->isFixedPointType()) &&
12139 "Unexpected type");
12140
12141 // Turn <4 x signed int> -> <4 x unsigned int>
12142 if (const auto *VTy = T->getAs<VectorType>())
12143 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
12144 VTy->getNumElements(), VTy->getVectorKind());
12145
12146 // For _BitInt, return an unsigned _BitInt with same width.
12147 if (const auto *EITy = T->getAs<BitIntType>())
12148 return getBitIntType(/*Unsigned=*/true, EITy->getNumBits());
12149
12150 // For enums, get the underlying integer type of the enum, and let the general
12151 // integer type signchanging code handle it.
12152 if (const auto *ED = T->getAsEnumDecl())
12153 T = ED->getIntegerType();
12154
12155 switch (T->castAs<BuiltinType>()->getKind()) {
12156 case BuiltinType::Char_U:
12157 // Plain `char` is mapped to `unsigned char` even if it's already unsigned
12158 case BuiltinType::Char_S:
12159 case BuiltinType::SChar:
12160 case BuiltinType::Char8:
12161 return UnsignedCharTy;
12162 case BuiltinType::Short:
12163 return UnsignedShortTy;
12164 case BuiltinType::Int:
12165 return UnsignedIntTy;
12166 case BuiltinType::Long:
12167 return UnsignedLongTy;
12168 case BuiltinType::LongLong:
12169 return UnsignedLongLongTy;
12170 case BuiltinType::Int128:
12171 return UnsignedInt128Ty;
12172 // wchar_t is special. It is either signed or not, but when it's signed,
12173 // there's no matching "unsigned wchar_t". Therefore we return the unsigned
12174 // version of its underlying type instead.
12175 case BuiltinType::WChar_S:
12176 return getUnsignedWCharType();
12177
12178 case BuiltinType::ShortAccum:
12179 return UnsignedShortAccumTy;
12180 case BuiltinType::Accum:
12181 return UnsignedAccumTy;
12182 case BuiltinType::LongAccum:
12183 return UnsignedLongAccumTy;
12184 case BuiltinType::SatShortAccum:
12186 case BuiltinType::SatAccum:
12187 return SatUnsignedAccumTy;
12188 case BuiltinType::SatLongAccum:
12190 case BuiltinType::ShortFract:
12191 return UnsignedShortFractTy;
12192 case BuiltinType::Fract:
12193 return UnsignedFractTy;
12194 case BuiltinType::LongFract:
12195 return UnsignedLongFractTy;
12196 case BuiltinType::SatShortFract:
12198 case BuiltinType::SatFract:
12199 return SatUnsignedFractTy;
12200 case BuiltinType::SatLongFract:
12202 default:
12203 assert((T->hasUnsignedIntegerRepresentation() ||
12204 T->isUnsignedFixedPointType()) &&
12205 "Unexpected signed integer or fixed point type");
12206 return T;
12207 }
12208}
12209
12211 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
12212 T->isFixedPointType()) &&
12213 "Unexpected type");
12214
12215 // Turn <4 x unsigned int> -> <4 x signed int>
12216 if (const auto *VTy = T->getAs<VectorType>())
12217 return getVectorType(getCorrespondingSignedType(VTy->getElementType()),
12218 VTy->getNumElements(), VTy->getVectorKind());
12219
12220 // For _BitInt, return a signed _BitInt with same width.
12221 if (const auto *EITy = T->getAs<BitIntType>())
12222 return getBitIntType(/*Unsigned=*/false, EITy->getNumBits());
12223
12224 // For enums, get the underlying integer type of the enum, and let the general
12225 // integer type signchanging code handle it.
12226 if (const auto *ED = T->getAsEnumDecl())
12227 T = ED->getIntegerType();
12228
12229 switch (T->castAs<BuiltinType>()->getKind()) {
12230 case BuiltinType::Char_S:
12231 // Plain `char` is mapped to `signed char` even if it's already signed
12232 case BuiltinType::Char_U:
12233 case BuiltinType::UChar:
12234 case BuiltinType::Char8:
12235 return SignedCharTy;
12236 case BuiltinType::UShort:
12237 return ShortTy;
12238 case BuiltinType::UInt:
12239 return IntTy;
12240 case BuiltinType::ULong:
12241 return LongTy;
12242 case BuiltinType::ULongLong:
12243 return LongLongTy;
12244 case BuiltinType::UInt128:
12245 return Int128Ty;
12246 // wchar_t is special. It is either unsigned or not, but when it's unsigned,
12247 // there's no matching "signed wchar_t". Therefore we return the signed
12248 // version of its underlying type instead.
12249 case BuiltinType::WChar_U:
12250 return getSignedWCharType();
12251
12252 case BuiltinType::UShortAccum:
12253 return ShortAccumTy;
12254 case BuiltinType::UAccum:
12255 return AccumTy;
12256 case BuiltinType::ULongAccum:
12257 return LongAccumTy;
12258 case BuiltinType::SatUShortAccum:
12259 return SatShortAccumTy;
12260 case BuiltinType::SatUAccum:
12261 return SatAccumTy;
12262 case BuiltinType::SatULongAccum:
12263 return SatLongAccumTy;
12264 case BuiltinType::UShortFract:
12265 return ShortFractTy;
12266 case BuiltinType::UFract:
12267 return FractTy;
12268 case BuiltinType::ULongFract:
12269 return LongFractTy;
12270 case BuiltinType::SatUShortFract:
12271 return SatShortFractTy;
12272 case BuiltinType::SatUFract:
12273 return SatFractTy;
12274 case BuiltinType::SatULongFract:
12275 return SatLongFractTy;
12276 default:
12277 assert(
12278 (T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) &&
12279 "Unexpected signed integer or fixed point type");
12280 return T;
12281 }
12282}
12283
12285
12288
12289//===----------------------------------------------------------------------===//
12290// Builtin Type Computation
12291//===----------------------------------------------------------------------===//
12292
12293/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
12294/// pointer over the consumed characters. This returns the resultant type. If
12295/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
12296/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
12297/// a vector of "i*".
12298///
12299/// RequiresICE is filled in on return to indicate whether the value is required
12300/// to be an Integer Constant Expression.
12301static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
12303 bool &RequiresICE,
12304 bool AllowTypeModifiers) {
12305 // Modifiers.
12306 int HowLong = 0;
12307 bool Signed = false, Unsigned = false;
12308 RequiresICE = false;
12309
12310 // Read the prefixed modifiers first.
12311 bool Done = false;
12312 #ifndef NDEBUG
12313 bool IsSpecial = false;
12314 #endif
12315 while (!Done) {
12316 switch (*Str++) {
12317 default: Done = true; --Str; break;
12318 case 'I':
12319 RequiresICE = true;
12320 break;
12321 case 'S':
12322 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
12323 assert(!Signed && "Can't use 'S' modifier multiple times!");
12324 Signed = true;
12325 break;
12326 case 'U':
12327 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
12328 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
12329 Unsigned = true;
12330 break;
12331 case 'L':
12332 assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers");
12333 assert(HowLong <= 2 && "Can't have LLLL modifier");
12334 ++HowLong;
12335 break;
12336 case 'N':
12337 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
12338 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12339 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
12340 #ifndef NDEBUG
12341 IsSpecial = true;
12342 #endif
12343 if (Context.getTargetInfo().getLongWidth() == 32)
12344 ++HowLong;
12345 break;
12346 case 'W':
12347 // This modifier represents int64 type.
12348 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12349 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
12350 #ifndef NDEBUG
12351 IsSpecial = true;
12352 #endif
12353 switch (Context.getTargetInfo().getInt64Type()) {
12354 default:
12355 llvm_unreachable("Unexpected integer type");
12357 HowLong = 1;
12358 break;
12360 HowLong = 2;
12361 break;
12362 }
12363 break;
12364 case 'Z':
12365 // This modifier represents int32 type.
12366 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12367 assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
12368 #ifndef NDEBUG
12369 IsSpecial = true;
12370 #endif
12371 switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) {
12372 default:
12373 llvm_unreachable("Unexpected integer type");
12375 HowLong = 0;
12376 break;
12378 HowLong = 1;
12379 break;
12381 HowLong = 2;
12382 break;
12383 }
12384 break;
12385 case 'O':
12386 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12387 assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
12388 #ifndef NDEBUG
12389 IsSpecial = true;
12390 #endif
12391 if (Context.getLangOpts().OpenCL)
12392 HowLong = 1;
12393 else
12394 HowLong = 2;
12395 break;
12396 }
12397 }
12398
12399 QualType Type;
12400
12401 // Read the base type.
12402 switch (*Str++) {
12403 default: llvm_unreachable("Unknown builtin type letter!");
12404 case 'x':
12405 assert(HowLong == 0 && !Signed && !Unsigned &&
12406 "Bad modifiers used with 'x'!");
12407 Type = Context.Float16Ty;
12408 break;
12409 case 'y':
12410 assert(HowLong == 0 && !Signed && !Unsigned &&
12411 "Bad modifiers used with 'y'!");
12412 Type = Context.BFloat16Ty;
12413 break;
12414 case 'v':
12415 assert(HowLong == 0 && !Signed && !Unsigned &&
12416 "Bad modifiers used with 'v'!");
12417 Type = Context.VoidTy;
12418 break;
12419 case 'h':
12420 assert(HowLong == 0 && !Signed && !Unsigned &&
12421 "Bad modifiers used with 'h'!");
12422 Type = Context.HalfTy;
12423 break;
12424 case 'f':
12425 assert(HowLong == 0 && !Signed && !Unsigned &&
12426 "Bad modifiers used with 'f'!");
12427 Type = Context.FloatTy;
12428 break;
12429 case 'd':
12430 assert(HowLong < 3 && !Signed && !Unsigned &&
12431 "Bad modifiers used with 'd'!");
12432 if (HowLong == 1)
12433 Type = Context.LongDoubleTy;
12434 else if (HowLong == 2)
12435 Type = Context.Float128Ty;
12436 else
12437 Type = Context.DoubleTy;
12438 break;
12439 case 's':
12440 assert(HowLong == 0 && "Bad modifiers used with 's'!");
12441 if (Unsigned)
12442 Type = Context.UnsignedShortTy;
12443 else
12444 Type = Context.ShortTy;
12445 break;
12446 case 'i':
12447 if (HowLong == 3)
12448 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
12449 else if (HowLong == 2)
12450 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
12451 else if (HowLong == 1)
12452 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
12453 else
12454 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
12455 break;
12456 case 'c':
12457 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
12458 if (Signed)
12459 Type = Context.SignedCharTy;
12460 else if (Unsigned)
12461 Type = Context.UnsignedCharTy;
12462 else
12463 Type = Context.CharTy;
12464 break;
12465 case 'b': // boolean
12466 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
12467 Type = Context.BoolTy;
12468 break;
12469 case 'z': // size_t.
12470 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
12471 Type = Context.getSizeType();
12472 break;
12473 case 'w': // wchar_t.
12474 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
12475 Type = Context.getWideCharType();
12476 break;
12477 case 'F':
12478 Type = Context.getCFConstantStringType();
12479 break;
12480 case 'G':
12481 Type = Context.getObjCIdType();
12482 break;
12483 case 'H':
12484 Type = Context.getObjCSelType();
12485 break;
12486 case 'M':
12487 Type = Context.getObjCSuperType();
12488 break;
12489 case 'a':
12490 Type = Context.getBuiltinVaListType();
12491 assert(!Type.isNull() && "builtin va list type not initialized!");
12492 break;
12493 case 'A':
12494 // This is a "reference" to a va_list; however, what exactly
12495 // this means depends on how va_list is defined. There are two
12496 // different kinds of va_list: ones passed by value, and ones
12497 // passed by reference. An example of a by-value va_list is
12498 // x86, where va_list is a char*. An example of by-ref va_list
12499 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
12500 // we want this argument to be a char*&; for x86-64, we want
12501 // it to be a __va_list_tag*.
12502 Type = Context.getBuiltinVaListType();
12503 assert(!Type.isNull() && "builtin va list type not initialized!");
12504 if (Type->isArrayType())
12505 Type = Context.getArrayDecayedType(Type);
12506 else
12507 Type = Context.getLValueReferenceType(Type);
12508 break;
12509 case 'q': {
12510 char *End;
12511 unsigned NumElements = strtoul(Str, &End, 10);
12512 assert(End != Str && "Missing vector size");
12513 Str = End;
12514
12515 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12516 RequiresICE, false);
12517 assert(!RequiresICE && "Can't require vector ICE");
12518
12519 Type = Context.getScalableVectorType(ElementType, NumElements);
12520 break;
12521 }
12522 case 'Q': {
12523 switch (*Str++) {
12524 case 'a': {
12525 Type = Context.SveCountTy;
12526 break;
12527 }
12528 case 'b': {
12529 Type = Context.AMDGPUBufferRsrcTy;
12530 break;
12531 }
12532 case 't': {
12533 Type = Context.AMDGPUTextureTy;
12534 break;
12535 }
12536 default:
12537 llvm_unreachable("Unexpected target builtin type");
12538 }
12539 break;
12540 }
12541 case 'V': {
12542 char *End;
12543 unsigned NumElements = strtoul(Str, &End, 10);
12544 assert(End != Str && "Missing vector size");
12545 Str = End;
12546
12547 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12548 RequiresICE, false);
12549 assert(!RequiresICE && "Can't require vector ICE");
12550
12551 // TODO: No way to make AltiVec vectors in builtins yet.
12552 Type = Context.getVectorType(ElementType, NumElements, VectorKind::Generic);
12553 break;
12554 }
12555 case 'E': {
12556 char *End;
12557
12558 unsigned NumElements = strtoul(Str, &End, 10);
12559 assert(End != Str && "Missing vector size");
12560
12561 Str = End;
12562
12563 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12564 false);
12565 Type = Context.getExtVectorType(ElementType, NumElements);
12566 break;
12567 }
12568 case 'X': {
12569 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12570 false);
12571 assert(!RequiresICE && "Can't require complex ICE");
12572 Type = Context.getComplexType(ElementType);
12573 break;
12574 }
12575 case 'Y':
12576 Type = Context.getPointerDiffType();
12577 break;
12578 case 'P':
12579 Type = Context.getFILEType();
12580 if (Type.isNull()) {
12582 return {};
12583 }
12584 break;
12585 case 'J':
12586 if (Signed)
12587 Type = Context.getsigjmp_bufType();
12588 else
12589 Type = Context.getjmp_bufType();
12590
12591 if (Type.isNull()) {
12593 return {};
12594 }
12595 break;
12596 case 'K':
12597 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
12598 Type = Context.getucontext_tType();
12599
12600 if (Type.isNull()) {
12602 return {};
12603 }
12604 break;
12605 case 'p':
12606 Type = Context.getProcessIDType();
12607 break;
12608 case 'm':
12609 Type = Context.MFloat8Ty;
12610 break;
12611 }
12612
12613 // If there are modifiers and if we're allowed to parse them, go for it.
12614 Done = !AllowTypeModifiers;
12615 while (!Done) {
12616 switch (char c = *Str++) {
12617 default: Done = true; --Str; break;
12618 case '*':
12619 case '&': {
12620 // Both pointers and references can have their pointee types
12621 // qualified with an address space.
12622 char *End;
12623 unsigned AddrSpace = strtoul(Str, &End, 10);
12624 if (End != Str) {
12625 // Note AddrSpace == 0 is not the same as an unspecified address space.
12626 Type = Context.getAddrSpaceQualType(
12627 Type,
12628 Context.getLangASForBuiltinAddressSpace(AddrSpace));
12629 Str = End;
12630 }
12631 if (c == '*')
12632 Type = Context.getPointerType(Type);
12633 else
12634 Type = Context.getLValueReferenceType(Type);
12635 break;
12636 }
12637 // FIXME: There's no way to have a built-in with an rvalue ref arg.
12638 case 'C':
12639 Type = Type.withConst();
12640 break;
12641 case 'D':
12642 Type = Context.getVolatileType(Type);
12643 break;
12644 case 'R':
12645 Type = Type.withRestrict();
12646 break;
12647 }
12648 }
12649
12650 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
12651 "Integer constant 'I' type must be an integer");
12652
12653 return Type;
12654}
12655
12656// On some targets such as PowerPC, some of the builtins are defined with custom
12657// type descriptors for target-dependent types. These descriptors are decoded in
12658// other functions, but it may be useful to be able to fall back to default
12659// descriptor decoding to define builtins mixing target-dependent and target-
12660// independent types. This function allows decoding one type descriptor with
12661// default decoding.
12662QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context,
12663 GetBuiltinTypeError &Error, bool &RequireICE,
12664 bool AllowTypeModifiers) const {
12665 return DecodeTypeFromStr(Str, Context, Error, RequireICE, AllowTypeModifiers);
12666}
12667
12668/// GetBuiltinType - Return the type for the specified builtin.
12671 unsigned *IntegerConstantArgs) const {
12672 const char *TypeStr = BuiltinInfo.getTypeString(Id);
12673 if (TypeStr[0] == '\0') {
12675 return {};
12676 }
12677
12678 SmallVector<QualType, 8> ArgTypes;
12679
12680 bool RequiresICE = false;
12681 Error = GE_None;
12682 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
12683 RequiresICE, true);
12684 if (Error != GE_None)
12685 return {};
12686
12687 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
12688
12689 while (TypeStr[0] && TypeStr[0] != '.') {
12690 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
12691 if (Error != GE_None)
12692 return {};
12693
12694 // If this argument is required to be an IntegerConstantExpression and the
12695 // caller cares, fill in the bitmask we return.
12696 if (RequiresICE && IntegerConstantArgs)
12697 *IntegerConstantArgs |= 1 << ArgTypes.size();
12698
12699 // Do array -> pointer decay. The builtin should use the decayed type.
12700 if (Ty->isArrayType())
12701 Ty = getArrayDecayedType(Ty);
12702
12703 ArgTypes.push_back(Ty);
12704 }
12705
12706 if (Id == Builtin::BI__GetExceptionInfo)
12707 return {};
12708
12709 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
12710 "'.' should only occur at end of builtin type list!");
12711
12712 bool Variadic = (TypeStr[0] == '.');
12713
12714 FunctionType::ExtInfo EI(Target->getDefaultCallingConv());
12715 if (BuiltinInfo.isNoReturn(Id))
12716 EI = EI.withNoReturn(true);
12717
12718 // We really shouldn't be making a no-proto type here.
12719 if (ArgTypes.empty() && Variadic && !getLangOpts().requiresStrictPrototypes())
12720 return getFunctionNoProtoType(ResType, EI);
12721
12723 EPI.ExtInfo = EI;
12724 EPI.Variadic = Variadic;
12725 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
12726 EPI.ExceptionSpec.Type =
12728
12729 return getFunctionType(ResType, ArgTypes, EPI);
12730}
12731
12733 const FunctionDecl *FD) {
12734 if (!FD->isExternallyVisible())
12735 return GVA_Internal;
12736
12737 // Non-user-provided functions get emitted as weak definitions with every
12738 // use, no matter whether they've been explicitly instantiated etc.
12739 if (!FD->isUserProvided())
12740 return GVA_DiscardableODR;
12741
12743 switch (FD->getTemplateSpecializationKind()) {
12744 case TSK_Undeclared:
12747 break;
12748
12750 return GVA_StrongODR;
12751
12752 // C++11 [temp.explicit]p10:
12753 // [ Note: The intent is that an inline function that is the subject of
12754 // an explicit instantiation declaration will still be implicitly
12755 // instantiated when used so that the body can be considered for
12756 // inlining, but that no out-of-line copy of the inline function would be
12757 // generated in the translation unit. -- end note ]
12760
12763 break;
12764 }
12765
12766 if (!FD->isInlined())
12767 return External;
12768
12769 if ((!Context.getLangOpts().CPlusPlus &&
12770 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12771 !FD->hasAttr<DLLExportAttr>()) ||
12772 FD->hasAttr<GNUInlineAttr>()) {
12773 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
12774
12775 // GNU or C99 inline semantics. Determine whether this symbol should be
12776 // externally visible.
12778 return External;
12779
12780 // C99 inline semantics, where the symbol is not externally visible.
12782 }
12783
12784 // Functions specified with extern and inline in -fms-compatibility mode
12785 // forcibly get emitted. While the body of the function cannot be later
12786 // replaced, the function definition cannot be discarded.
12787 if (FD->isMSExternInline())
12788 return GVA_StrongODR;
12789
12790 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12792 cast<CXXConstructorDecl>(FD)->isInheritingConstructor())
12793 // Our approach to inheriting constructors is fundamentally different from
12794 // that used by the MS ABI, so keep our inheriting constructor thunks
12795 // internal rather than trying to pick an unambiguous mangling for them.
12796 return GVA_Internal;
12797
12798 return GVA_DiscardableODR;
12799}
12800
12802 const Decl *D, GVALinkage L) {
12803 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
12804 // dllexport/dllimport on inline functions.
12805 if (D->hasAttr<DLLImportAttr>()) {
12806 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
12808 } else if (D->hasAttr<DLLExportAttr>()) {
12809 if (L == GVA_DiscardableODR)
12810 return GVA_StrongODR;
12811 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) {
12812 // Device-side functions with __global__ attribute must always be
12813 // visible externally so they can be launched from host.
12814 if (D->hasAttr<CUDAGlobalAttr>() &&
12815 (L == GVA_DiscardableODR || L == GVA_Internal))
12816 return GVA_StrongODR;
12817 // Single source offloading languages like CUDA/HIP need to be able to
12818 // access static device variables from host code of the same compilation
12819 // unit. This is done by externalizing the static variable with a shared
12820 // name between the host and device compilation which is the same for the
12821 // same compilation unit whereas different among different compilation
12822 // units.
12823 if (Context.shouldExternalize(D))
12824 return GVA_StrongExternal;
12825 }
12826 return L;
12827}
12828
12829/// Adjust the GVALinkage for a declaration based on what an external AST source
12830/// knows about whether there can be other definitions of this declaration.
12831static GVALinkage
12833 GVALinkage L) {
12834 ExternalASTSource *Source = Ctx.getExternalSource();
12835 if (!Source)
12836 return L;
12837
12838 switch (Source->hasExternalDefinitions(D)) {
12840 // Other translation units rely on us to provide the definition.
12841 if (L == GVA_DiscardableODR)
12842 return GVA_StrongODR;
12843 break;
12844
12847
12849 break;
12850 }
12851 return L;
12852}
12853
12859
12861 const VarDecl *VD) {
12862 // As an extension for interactive REPLs, make sure constant variables are
12863 // only emitted once instead of LinkageComputer::getLVForNamespaceScopeDecl
12864 // marking them as internal.
12865 if (Context.getLangOpts().CPlusPlus &&
12866 Context.getLangOpts().IncrementalExtensions &&
12867 VD->getType().isConstQualified() &&
12868 !VD->getType().isVolatileQualified() && !VD->isInline() &&
12870 return GVA_DiscardableODR;
12871
12872 if (!VD->isExternallyVisible())
12873 return GVA_Internal;
12874
12875 if (VD->isStaticLocal()) {
12876 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
12877 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
12878 LexicalContext = LexicalContext->getLexicalParent();
12879
12880 // ObjC Blocks can create local variables that don't have a FunctionDecl
12881 // LexicalContext.
12882 if (!LexicalContext)
12883 return GVA_DiscardableODR;
12884
12885 // Otherwise, let the static local variable inherit its linkage from the
12886 // nearest enclosing function.
12887 auto StaticLocalLinkage =
12888 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
12889
12890 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
12891 // be emitted in any object with references to the symbol for the object it
12892 // contains, whether inline or out-of-line."
12893 // Similar behavior is observed with MSVC. An alternative ABI could use
12894 // StrongODR/AvailableExternally to match the function, but none are
12895 // known/supported currently.
12896 if (StaticLocalLinkage == GVA_StrongODR ||
12897 StaticLocalLinkage == GVA_AvailableExternally)
12898 return GVA_DiscardableODR;
12899 return StaticLocalLinkage;
12900 }
12901
12902 // MSVC treats in-class initialized static data members as definitions.
12903 // By giving them non-strong linkage, out-of-line definitions won't
12904 // cause link errors.
12905 if (Context.isMSStaticDataMemberInlineDefinition(VD))
12906 return GVA_DiscardableODR;
12907
12908 // Most non-template variables have strong linkage; inline variables are
12909 // linkonce_odr or (occasionally, for compatibility) weak_odr.
12910 GVALinkage StrongLinkage;
12911 switch (Context.getInlineVariableDefinitionKind(VD)) {
12913 StrongLinkage = GVA_StrongExternal;
12914 break;
12917 StrongLinkage = GVA_DiscardableODR;
12918 break;
12920 StrongLinkage = GVA_StrongODR;
12921 break;
12922 }
12923
12924 switch (VD->getTemplateSpecializationKind()) {
12925 case TSK_Undeclared:
12926 return StrongLinkage;
12927
12929 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12930 VD->isStaticDataMember()
12932 : StrongLinkage;
12933
12935 return GVA_StrongODR;
12936
12939
12941 return GVA_DiscardableODR;
12942 }
12943
12944 llvm_unreachable("Invalid Linkage!");
12945}
12946
12952
12954 if (const auto *VD = dyn_cast<VarDecl>(D)) {
12955 if (!VD->isFileVarDecl())
12956 return false;
12957 // Global named register variables (GNU extension) are never emitted.
12958 if (VD->getStorageClass() == SC_Register)
12959 return false;
12960 if (VD->getDescribedVarTemplate() ||
12962 return false;
12963 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
12964 // We never need to emit an uninstantiated function template.
12965 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
12966 return false;
12967 } else if (isa<PragmaCommentDecl>(D))
12968 return true;
12970 return true;
12971 else if (isa<OMPRequiresDecl>(D))
12972 return true;
12973 else if (isa<OMPThreadPrivateDecl>(D))
12974 return !D->getDeclContext()->isDependentContext();
12975 else if (isa<OMPAllocateDecl>(D))
12976 return !D->getDeclContext()->isDependentContext();
12978 return !D->getDeclContext()->isDependentContext();
12979 else if (isa<ImportDecl>(D))
12980 return true;
12981 else
12982 return false;
12983
12984 // If this is a member of a class template, we do not need to emit it.
12986 return false;
12987
12988 // Weak references don't produce any output by themselves.
12989 if (D->hasAttr<WeakRefAttr>())
12990 return false;
12991
12992 // SYCL device compilation requires that functions defined with the
12993 // sycl_kernel_entry_point or sycl_external attributes be emitted. All
12994 // other entities are emitted only if they are used by a function
12995 // defined with one of those attributes.
12996 if (LangOpts.SYCLIsDevice)
12997 return isa<FunctionDecl>(D) && (D->hasAttr<SYCLKernelEntryPointAttr>() ||
12998 D->hasAttr<SYCLExternalAttr>());
12999
13000 // Aliases and used decls are required.
13001 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
13002 return true;
13003
13004 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
13005 // Forward declarations aren't required.
13006 if (!FD->doesThisDeclarationHaveABody())
13007 return FD->doesDeclarationForceExternallyVisibleDefinition();
13008
13009 // Constructors and destructors are required.
13010 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
13011 return true;
13012
13013 // The key function for a class is required. This rule only comes
13014 // into play when inline functions can be key functions, though.
13015 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
13016 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
13017 const CXXRecordDecl *RD = MD->getParent();
13018 if (MD->isOutOfLine() && RD->isDynamicClass()) {
13019 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
13020 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
13021 return true;
13022 }
13023 }
13024 }
13025
13027
13028 // static, static inline, always_inline, and extern inline functions can
13029 // always be deferred. Normal inline functions can be deferred in C99/C++.
13030 // Implicit template instantiations can also be deferred in C++.
13032 }
13033
13034 const auto *VD = cast<VarDecl>(D);
13035 assert(VD->isFileVarDecl() && "Expected file scoped var");
13036
13037 // If the decl is marked as `declare target to`, it should be emitted for the
13038 // host and for the device.
13039 if (LangOpts.OpenMP &&
13040 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
13041 return true;
13042
13043 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
13045 return false;
13046
13047 if (VD->shouldEmitInExternalSource())
13048 return false;
13049
13050 // Variables that can be needed in other TUs are required.
13053 return true;
13054
13055 // We never need to emit a variable that is available in another TU.
13057 return false;
13058
13059 // Variables that have destruction with side-effects are required.
13060 if (VD->needsDestruction(*this))
13061 return true;
13062
13063 // Variables that have initialization with side-effects are required.
13064 if (VD->hasInitWithSideEffects())
13065 return true;
13066
13067 // Likewise, variables with tuple-like bindings are required if their
13068 // bindings have side-effects.
13069 if (const auto *DD = dyn_cast<DecompositionDecl>(VD)) {
13070 for (const auto *BD : DD->flat_bindings())
13071 if (const auto *BindingVD = BD->getHoldingVar())
13072 if (DeclMustBeEmitted(BindingVD))
13073 return true;
13074 }
13075
13076 return false;
13077}
13078
13080 const FunctionDecl *FD,
13081 llvm::function_ref<void(FunctionDecl *)> Pred) const {
13082 assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
13083 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
13084 FD = FD->getMostRecentDecl();
13085 // FIXME: The order of traversal here matters and depends on the order of
13086 // lookup results, which happens to be (mostly) oldest-to-newest, but we
13087 // shouldn't rely on that.
13088 for (auto *CurDecl :
13090 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
13091 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
13092 SeenDecls.insert(CurFD).second) {
13093 Pred(CurFD);
13094 }
13095 }
13096}
13097
13099 bool IsCXXMethod) const {
13100 // Pass through to the C++ ABI object
13101 if (IsCXXMethod)
13102 return ABI->getDefaultMethodCallConv(IsVariadic);
13103
13104 switch (LangOpts.getDefaultCallingConv()) {
13106 break;
13108 return CC_C;
13110 if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
13111 return CC_X86FastCall;
13112 break;
13114 if (!IsVariadic)
13115 return CC_X86StdCall;
13116 break;
13118 // __vectorcall cannot be applied to variadic functions.
13119 if (!IsVariadic)
13120 return CC_X86VectorCall;
13121 break;
13123 // __regcall cannot be applied to variadic functions.
13124 if (!IsVariadic)
13125 return CC_X86RegCall;
13126 break;
13128 if (!IsVariadic)
13129 return CC_M68kRTD;
13130 break;
13131 }
13132 return Target->getDefaultCallingConv();
13133}
13134
13136 // Pass through to the C++ ABI object
13137 return ABI->isNearlyEmpty(RD);
13138}
13139
13141 if (!VTContext) {
13142 auto ABI = Target->getCXXABI();
13143 if (ABI.isMicrosoft())
13144 VTContext.reset(new MicrosoftVTableContext(*this));
13145 else {
13146 auto ComponentLayout = getLangOpts().RelativeCXXABIVTables
13149 VTContext.reset(new ItaniumVTableContext(*this, ComponentLayout));
13150 }
13151 }
13152 return VTContext.get();
13153}
13154
13156 if (!T)
13157 T = Target;
13158 switch (T->getCXXABI().getKind()) {
13159 case TargetCXXABI::AppleARM64:
13160 case TargetCXXABI::Fuchsia:
13161 case TargetCXXABI::GenericAArch64:
13162 case TargetCXXABI::GenericItanium:
13163 case TargetCXXABI::GenericARM:
13164 case TargetCXXABI::GenericMIPS:
13165 case TargetCXXABI::iOS:
13166 case TargetCXXABI::WebAssembly:
13167 case TargetCXXABI::WatchOS:
13168 case TargetCXXABI::XL:
13170 case TargetCXXABI::Microsoft:
13172 }
13173 llvm_unreachable("Unsupported ABI");
13174}
13175
13177 assert(T.getCXXABI().getKind() != TargetCXXABI::Microsoft &&
13178 "Device mangle context does not support Microsoft mangling.");
13179 switch (T.getCXXABI().getKind()) {
13180 case TargetCXXABI::AppleARM64:
13181 case TargetCXXABI::Fuchsia:
13182 case TargetCXXABI::GenericAArch64:
13183 case TargetCXXABI::GenericItanium:
13184 case TargetCXXABI::GenericARM:
13185 case TargetCXXABI::GenericMIPS:
13186 case TargetCXXABI::iOS:
13187 case TargetCXXABI::WebAssembly:
13188 case TargetCXXABI::WatchOS:
13189 case TargetCXXABI::XL:
13191 *this, getDiagnostics(),
13192 [](ASTContext &, const NamedDecl *ND) -> UnsignedOrNone {
13193 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
13194 return RD->getDeviceLambdaManglingNumber();
13195 return std::nullopt;
13196 },
13197 /*IsAux=*/true);
13198 case TargetCXXABI::Microsoft:
13200 /*IsAux=*/true);
13201 }
13202 llvm_unreachable("Unsupported ABI");
13203}
13204
13205CXXABI::~CXXABI() = default;
13206
13208 return ASTRecordLayouts.getMemorySize() +
13209 llvm::capacity_in_bytes(ObjCLayouts) +
13210 llvm::capacity_in_bytes(KeyFunctions) +
13211 llvm::capacity_in_bytes(ObjCImpls) +
13212 llvm::capacity_in_bytes(BlockVarCopyInits) +
13213 llvm::capacity_in_bytes(DeclAttrs) +
13214 llvm::capacity_in_bytes(TemplateOrInstantiation) +
13215 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
13216 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
13217 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
13218 llvm::capacity_in_bytes(OverriddenMethods) +
13219 llvm::capacity_in_bytes(Types) +
13220 llvm::capacity_in_bytes(VariableArrayTypes);
13221}
13222
13223/// getIntTypeForBitwidth -
13224/// sets integer QualTy according to specified details:
13225/// bitwidth, signed/unsigned.
13226/// Returns empty type if there is no appropriate target types.
13228 unsigned Signed) const {
13230 CanQualType QualTy = getFromTargetType(Ty);
13231 if (!QualTy && DestWidth == 128)
13232 return Signed ? Int128Ty : UnsignedInt128Ty;
13233 return QualTy;
13234}
13235
13236/// getRealTypeForBitwidth -
13237/// sets floating point QualTy according to specified bitwidth.
13238/// Returns empty type if there is no appropriate target types.
13240 FloatModeKind ExplicitType) const {
13241 FloatModeKind Ty =
13242 getTargetInfo().getRealTypeByWidth(DestWidth, ExplicitType);
13243 switch (Ty) {
13245 return HalfTy;
13247 return FloatTy;
13249 return DoubleTy;
13251 return LongDoubleTy;
13253 return Float128Ty;
13255 return Ibm128Ty;
13257 return {};
13258 }
13259
13260 llvm_unreachable("Unhandled TargetInfo::RealType value");
13261}
13262
13263void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
13264 if (Number <= 1)
13265 return;
13266
13267 MangleNumbers[ND] = Number;
13268
13269 if (Listener)
13270 Listener->AddedManglingNumber(ND, Number);
13271}
13272
13274 bool ForAuxTarget) const {
13275 auto I = MangleNumbers.find(ND);
13276 unsigned Res = I != MangleNumbers.end() ? I->second : 1;
13277 // CUDA/HIP host compilation encodes host and device mangling numbers
13278 // as lower and upper half of 32 bit integer.
13279 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice) {
13280 Res = ForAuxTarget ? Res >> 16 : Res & 0xFFFF;
13281 } else {
13282 assert(!ForAuxTarget && "Only CUDA/HIP host compilation supports mangling "
13283 "number for aux target");
13284 }
13285 return Res > 1 ? Res : 1;
13286}
13287
13288void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
13289 if (Number <= 1)
13290 return;
13291
13292 StaticLocalNumbers[VD] = Number;
13293
13294 if (Listener)
13295 Listener->AddedStaticLocalNumbers(VD, Number);
13296}
13297
13299 auto I = StaticLocalNumbers.find(VD);
13300 return I != StaticLocalNumbers.end() ? I->second : 1;
13301}
13302
13304 bool IsDestroying) {
13305 if (!IsDestroying) {
13306 assert(!DestroyingOperatorDeletes.contains(FD->getCanonicalDecl()));
13307 return;
13308 }
13309 DestroyingOperatorDeletes.insert(FD->getCanonicalDecl());
13310}
13311
13313 return DestroyingOperatorDeletes.contains(FD->getCanonicalDecl());
13314}
13315
13317 bool IsTypeAware) {
13318 if (!IsTypeAware) {
13319 assert(!TypeAwareOperatorNewAndDeletes.contains(FD->getCanonicalDecl()));
13320 return;
13321 }
13322 TypeAwareOperatorNewAndDeletes.insert(FD->getCanonicalDecl());
13323}
13324
13326 return TypeAwareOperatorNewAndDeletes.contains(FD->getCanonicalDecl());
13327}
13328
13331 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13332 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
13333 if (!MCtx)
13335 return *MCtx;
13336}
13337
13340 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13341 std::unique_ptr<MangleNumberingContext> &MCtx =
13342 ExtraMangleNumberingContexts[D];
13343 if (!MCtx)
13345 return *MCtx;
13346}
13347
13348std::unique_ptr<MangleNumberingContext>
13350 return ABI->createMangleNumberingContext();
13351}
13352
13353const CXXConstructorDecl *
13355 return ABI->getCopyConstructorForExceptionObject(
13357}
13358
13360 CXXConstructorDecl *CD) {
13361 return ABI->addCopyConstructorForExceptionObject(
13364}
13365
13367 TypedefNameDecl *DD) {
13368 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
13369}
13370
13373 return ABI->getTypedefNameForUnnamedTagDecl(TD);
13374}
13375
13377 DeclaratorDecl *DD) {
13378 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
13379}
13380
13382 return ABI->getDeclaratorForUnnamedTagDecl(TD);
13383}
13384
13386 ParamIndices[D] = index;
13387}
13388
13390 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
13391 assert(I != ParamIndices.end() &&
13392 "ParmIndices lacks entry set by ParmVarDecl");
13393 return I->second;
13394}
13395
13397 unsigned Length) const {
13398 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
13399 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
13400 EltTy = EltTy.withConst();
13401
13402 EltTy = adjustStringLiteralBaseType(EltTy);
13403
13404 // Get an array type for the string, according to C99 6.4.5. This includes
13405 // the null terminator character.
13406 return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr,
13407 ArraySizeModifier::Normal, /*IndexTypeQuals*/ 0);
13408}
13409
13412 StringLiteral *&Result = StringLiteralCache[Key];
13413 if (!Result)
13415 *this, Key, StringLiteralKind::Ordinary,
13416 /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()),
13417 SourceLocation());
13418 return Result;
13419}
13420
13421MSGuidDecl *
13423 assert(MSGuidTagDecl && "building MS GUID without MS extensions?");
13424
13425 llvm::FoldingSetNodeID ID;
13426 MSGuidDecl::Profile(ID, Parts);
13427
13428 void *InsertPos;
13429 if (MSGuidDecl *Existing = MSGuidDecls.FindNodeOrInsertPos(ID, InsertPos))
13430 return Existing;
13431
13432 QualType GUIDType = getMSGuidType().withConst();
13433 MSGuidDecl *New = MSGuidDecl::Create(*this, GUIDType, Parts);
13434 MSGuidDecls.InsertNode(New, InsertPos);
13435 return New;
13436}
13437
13440 const APValue &APVal) const {
13441 llvm::FoldingSetNodeID ID;
13443
13444 void *InsertPos;
13445 if (UnnamedGlobalConstantDecl *Existing =
13446 UnnamedGlobalConstantDecls.FindNodeOrInsertPos(ID, InsertPos))
13447 return Existing;
13448
13450 UnnamedGlobalConstantDecl::Create(*this, Ty, APVal);
13451 UnnamedGlobalConstantDecls.InsertNode(New, InsertPos);
13452 return New;
13453}
13454
13457 assert(T->isRecordType() && "template param object of unexpected type");
13458
13459 // C++ [temp.param]p8:
13460 // [...] a static storage duration object of type 'const T' [...]
13461 T.addConst();
13462
13463 llvm::FoldingSetNodeID ID;
13465
13466 void *InsertPos;
13467 if (TemplateParamObjectDecl *Existing =
13468 TemplateParamObjectDecls.FindNodeOrInsertPos(ID, InsertPos))
13469 return Existing;
13470
13471 TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(*this, T, V);
13472 TemplateParamObjectDecls.InsertNode(New, InsertPos);
13473 return New;
13474}
13475
13477 const llvm::Triple &T = getTargetInfo().getTriple();
13478 if (!T.isOSDarwin())
13479 return false;
13480
13481 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
13482 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
13483 return false;
13484
13485 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
13486 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
13487 uint64_t Size = sizeChars.getQuantity();
13488 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
13489 unsigned Align = alignChars.getQuantity();
13490 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
13491 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
13492}
13493
13494bool
13496 const ObjCMethodDecl *MethodImpl) {
13497 // No point trying to match an unavailable/deprecated mothod.
13498 if (MethodDecl->hasAttr<UnavailableAttr>()
13499 || MethodDecl->hasAttr<DeprecatedAttr>())
13500 return false;
13501 if (MethodDecl->getObjCDeclQualifier() !=
13502 MethodImpl->getObjCDeclQualifier())
13503 return false;
13504 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
13505 return false;
13506
13507 if (MethodDecl->param_size() != MethodImpl->param_size())
13508 return false;
13509
13510 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
13511 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
13512 EF = MethodDecl->param_end();
13513 IM != EM && IF != EF; ++IM, ++IF) {
13514 const ParmVarDecl *DeclVar = (*IF);
13515 const ParmVarDecl *ImplVar = (*IM);
13516 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
13517 return false;
13518 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
13519 return false;
13520 }
13521
13522 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
13523}
13524
13526 LangAS AS;
13528 AS = LangAS::Default;
13529 else
13530 AS = QT->getPointeeType().getAddressSpace();
13531
13533}
13534
13537}
13538
13539bool ASTContext::hasSameExpr(const Expr *X, const Expr *Y) const {
13540 if (X == Y)
13541 return true;
13542 if (!X || !Y)
13543 return false;
13544 llvm::FoldingSetNodeID IDX, IDY;
13545 X->Profile(IDX, *this, /*Canonical=*/true);
13546 Y->Profile(IDY, *this, /*Canonical=*/true);
13547 return IDX == IDY;
13548}
13549
13550// The getCommon* helpers return, for given 'same' X and Y entities given as
13551// inputs, another entity which is also the 'same' as the inputs, but which
13552// is closer to the canonical form of the inputs, each according to a given
13553// criteria.
13554// The getCommon*Checked variants are 'null inputs not-allowed' equivalents of
13555// the regular ones.
13556
13558 if (!declaresSameEntity(X, Y))
13559 return nullptr;
13560 for (const Decl *DX : X->redecls()) {
13561 // If we reach Y before reaching the first decl, that means X is older.
13562 if (DX == Y)
13563 return X;
13564 // If we reach the first decl, then Y is older.
13565 if (DX->isFirstDecl())
13566 return Y;
13567 }
13568 llvm_unreachable("Corrupt redecls chain");
13569}
13570
13571template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
13572static T *getCommonDecl(T *X, T *Y) {
13573 return cast_or_null<T>(
13574 getCommonDecl(const_cast<Decl *>(cast_or_null<Decl>(X)),
13575 const_cast<Decl *>(cast_or_null<Decl>(Y))));
13576}
13577
13578template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
13579static T *getCommonDeclChecked(T *X, T *Y) {
13580 return cast<T>(getCommonDecl(const_cast<Decl *>(cast<Decl>(X)),
13581 const_cast<Decl *>(cast<Decl>(Y))));
13582}
13583
13585 TemplateName Y,
13586 bool IgnoreDeduced = false) {
13587 if (X.getAsVoidPointer() == Y.getAsVoidPointer())
13588 return X;
13589 // FIXME: There are cases here where we could find a common template name
13590 // with more sugar. For example one could be a SubstTemplateTemplate*
13591 // replacing the other.
13592 TemplateName CX = Ctx.getCanonicalTemplateName(X, IgnoreDeduced);
13593 if (CX.getAsVoidPointer() !=
13595 return TemplateName();
13596 return CX;
13597}
13598
13601 bool IgnoreDeduced) {
13602 TemplateName R = getCommonTemplateName(Ctx, X, Y, IgnoreDeduced);
13603 assert(R.getAsVoidPointer() != nullptr);
13604 return R;
13605}
13606
13608 ArrayRef<QualType> Ys, bool Unqualified = false) {
13609 assert(Xs.size() == Ys.size());
13610 SmallVector<QualType, 8> Rs(Xs.size());
13611 for (size_t I = 0; I < Rs.size(); ++I)
13612 Rs[I] = Ctx.getCommonSugaredType(Xs[I], Ys[I], Unqualified);
13613 return Rs;
13614}
13615
13616template <class T>
13617static SourceLocation getCommonAttrLoc(const T *X, const T *Y) {
13618 return X->getAttributeLoc() == Y->getAttributeLoc() ? X->getAttributeLoc()
13619 : SourceLocation();
13620}
13621
13623 const TemplateArgument &X,
13624 const TemplateArgument &Y) {
13625 if (X.getKind() != Y.getKind())
13626 return TemplateArgument();
13627
13628 switch (X.getKind()) {
13630 if (!Ctx.hasSameType(X.getAsType(), Y.getAsType()))
13631 return TemplateArgument();
13632 return TemplateArgument(
13633 Ctx.getCommonSugaredType(X.getAsType(), Y.getAsType()));
13635 if (!Ctx.hasSameType(X.getNullPtrType(), Y.getNullPtrType()))
13636 return TemplateArgument();
13637 return TemplateArgument(
13638 Ctx.getCommonSugaredType(X.getNullPtrType(), Y.getNullPtrType()),
13639 /*Unqualified=*/true);
13641 if (!Ctx.hasSameType(X.getAsExpr()->getType(), Y.getAsExpr()->getType()))
13642 return TemplateArgument();
13643 // FIXME: Try to keep the common sugar.
13644 return X;
13646 TemplateName TX = X.getAsTemplate(), TY = Y.getAsTemplate();
13647 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
13648 if (!CTN.getAsVoidPointer())
13649 return TemplateArgument();
13650 return TemplateArgument(CTN);
13651 }
13653 TemplateName TX = X.getAsTemplateOrTemplatePattern(),
13655 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
13656 if (!CTN.getAsVoidPointer())
13657 return TemplateName();
13658 auto NExpX = X.getNumTemplateExpansions();
13659 assert(NExpX == Y.getNumTemplateExpansions());
13660 return TemplateArgument(CTN, NExpX);
13661 }
13662 default:
13663 // FIXME: Handle the other argument kinds.
13664 return X;
13665 }
13666}
13667
13672 if (Xs.size() != Ys.size())
13673 return true;
13674 R.resize(Xs.size());
13675 for (size_t I = 0; I < R.size(); ++I) {
13676 R[I] = getCommonTemplateArgument(Ctx, Xs[I], Ys[I]);
13677 if (R[I].isNull())
13678 return true;
13679 }
13680 return false;
13681}
13682
13687 bool Different = getCommonTemplateArguments(Ctx, R, Xs, Ys);
13688 assert(!Different);
13689 (void)Different;
13690 return R;
13691}
13692
13693template <class T>
13695 bool IsSame) {
13696 ElaboratedTypeKeyword KX = X->getKeyword(), KY = Y->getKeyword();
13697 if (KX == KY)
13698 return KX;
13700 assert(!IsSame || KX == getCanonicalElaboratedTypeKeyword(KY));
13701 return KX;
13702}
13703
13704/// Returns a NestedNameSpecifier which has only the common sugar
13705/// present in both NNS1 and NNS2.
13708 NestedNameSpecifier NNS2, bool IsSame) {
13709 // If they are identical, all sugar is common.
13710 if (NNS1 == NNS2)
13711 return NNS1;
13712
13713 // IsSame implies both Qualifiers are equivalent.
13714 NestedNameSpecifier Canon = NNS1.getCanonical();
13715 if (Canon != NNS2.getCanonical()) {
13716 assert(!IsSame && "Should be the same NestedNameSpecifier");
13717 // If they are not the same, there is nothing to unify.
13718 return std::nullopt;
13719 }
13720
13721 NestedNameSpecifier R = std::nullopt;
13722 NestedNameSpecifier::Kind Kind = NNS1.getKind();
13723 assert(Kind == NNS2.getKind());
13724 switch (Kind) {
13726 auto [Namespace1, Prefix1] = NNS1.getAsNamespaceAndPrefix();
13727 auto [Namespace2, Prefix2] = NNS2.getAsNamespaceAndPrefix();
13728 auto Kind = Namespace1->getKind();
13729 if (Kind != Namespace2->getKind() ||
13730 (Kind == Decl::NamespaceAlias &&
13731 !declaresSameEntity(Namespace1, Namespace2))) {
13733 Ctx,
13734 ::getCommonDeclChecked(Namespace1->getNamespace(),
13735 Namespace2->getNamespace()),
13736 /*Prefix=*/std::nullopt);
13737 break;
13738 }
13739 // The prefixes for namespaces are not significant, its declaration
13740 // identifies it uniquely.
13741 NestedNameSpecifier Prefix = ::getCommonNNS(Ctx, Prefix1, Prefix2,
13742 /*IsSame=*/false);
13743 R = NestedNameSpecifier(Ctx, ::getCommonDeclChecked(Namespace1, Namespace2),
13744 Prefix);
13745 break;
13746 }
13748 const Type *T1 = NNS1.getAsType(), *T2 = NNS2.getAsType();
13749 const Type *T = Ctx.getCommonSugaredType(QualType(T1, 0), QualType(T2, 0),
13750 /*Unqualified=*/true)
13751 .getTypePtr();
13753 break;
13754 }
13756 // FIXME: Can __super even be used with data members?
13757 // If it's only usable in functions, we will never see it here,
13758 // unless we save the qualifiers used in function types.
13759 // In that case, it might be possible NNS2 is a type,
13760 // in which case we should degrade the result to
13761 // a CXXRecordType.
13763 NNS2.getAsMicrosoftSuper()));
13764 break;
13765 }
13768 // These are singletons.
13769 llvm_unreachable("singletons did not compare equal");
13770 }
13771 assert(R.getCanonical() == Canon);
13772 return R;
13773}
13774
13775template <class T>
13777 const T *Y, bool IsSame) {
13778 return ::getCommonNNS(Ctx, X->getQualifier(), Y->getQualifier(), IsSame);
13779}
13780
13781template <class T>
13782static QualType getCommonElementType(const ASTContext &Ctx, const T *X,
13783 const T *Y) {
13784 return Ctx.getCommonSugaredType(X->getElementType(), Y->getElementType());
13785}
13786
13787template <class T>
13789 Qualifiers &QX, const T *Y,
13790 Qualifiers &QY) {
13791 QualType EX = X->getElementType(), EY = Y->getElementType();
13792 QualType R = Ctx.getCommonSugaredType(EX, EY,
13793 /*Unqualified=*/true);
13794 // Qualifiers common to both element types.
13795 Qualifiers RQ = R.getQualifiers();
13796 // For each side, move to the top level any qualifiers which are not common to
13797 // both element types. The caller must assume top level qualifiers might
13798 // be different, even if they are the same type, and can be treated as sugar.
13799 QX += EX.getQualifiers() - RQ;
13800 QY += EY.getQualifiers() - RQ;
13801 return R;
13802}
13803
13804template <class T>
13805static QualType getCommonPointeeType(const ASTContext &Ctx, const T *X,
13806 const T *Y) {
13807 return Ctx.getCommonSugaredType(X->getPointeeType(), Y->getPointeeType());
13808}
13809
13810template <class T>
13811static auto *getCommonSizeExpr(const ASTContext &Ctx, T *X, T *Y) {
13812 assert(Ctx.hasSameExpr(X->getSizeExpr(), Y->getSizeExpr()));
13813 return X->getSizeExpr();
13814}
13815
13816static auto getCommonSizeModifier(const ArrayType *X, const ArrayType *Y) {
13817 assert(X->getSizeModifier() == Y->getSizeModifier());
13818 return X->getSizeModifier();
13819}
13820
13822 const ArrayType *Y) {
13823 assert(X->getIndexTypeCVRQualifiers() == Y->getIndexTypeCVRQualifiers());
13824 return X->getIndexTypeCVRQualifiers();
13825}
13826
13827// Merges two type lists such that the resulting vector will contain
13828// each type (in a canonical sense) only once, in the order they appear
13829// from X to Y. If they occur in both X and Y, the result will contain
13830// the common sugared type between them.
13831static void mergeTypeLists(const ASTContext &Ctx,
13834 llvm::DenseMap<QualType, unsigned> Found;
13835 for (auto Ts : {X, Y}) {
13836 for (QualType T : Ts) {
13837 auto Res = Found.try_emplace(Ctx.getCanonicalType(T), Out.size());
13838 if (!Res.second) {
13839 QualType &U = Out[Res.first->second];
13840 U = Ctx.getCommonSugaredType(U, T);
13841 } else {
13842 Out.emplace_back(T);
13843 }
13844 }
13845 }
13846}
13847
13848FunctionProtoType::ExceptionSpecInfo
13851 SmallVectorImpl<QualType> &ExceptionTypeStorage,
13852 bool AcceptDependent) const {
13853 ExceptionSpecificationType EST1 = ESI1.Type, EST2 = ESI2.Type;
13854
13855 // If either of them can throw anything, that is the result.
13856 for (auto I : {EST_None, EST_MSAny, EST_NoexceptFalse}) {
13857 if (EST1 == I)
13858 return ESI1;
13859 if (EST2 == I)
13860 return ESI2;
13861 }
13862
13863 // If either of them is non-throwing, the result is the other.
13864 for (auto I :
13866 if (EST1 == I)
13867 return ESI2;
13868 if (EST2 == I)
13869 return ESI1;
13870 }
13871
13872 // If we're left with value-dependent computed noexcept expressions, we're
13873 // stuck. Before C++17, we can just drop the exception specification entirely,
13874 // since it's not actually part of the canonical type. And this should never
13875 // happen in C++17, because it would mean we were computing the composite
13876 // pointer type of dependent types, which should never happen.
13877 if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) {
13878 assert(AcceptDependent &&
13879 "computing composite pointer type of dependent types");
13881 }
13882
13883 // Switch over the possibilities so that people adding new values know to
13884 // update this function.
13885 switch (EST1) {
13886 case EST_None:
13887 case EST_DynamicNone:
13888 case EST_MSAny:
13889 case EST_BasicNoexcept:
13891 case EST_NoexceptFalse:
13892 case EST_NoexceptTrue:
13893 case EST_NoThrow:
13894 llvm_unreachable("These ESTs should be handled above");
13895
13896 case EST_Dynamic: {
13897 // This is the fun case: both exception specifications are dynamic. Form
13898 // the union of the two lists.
13899 assert(EST2 == EST_Dynamic && "other cases should already be handled");
13900 mergeTypeLists(*this, ExceptionTypeStorage, ESI1.Exceptions,
13901 ESI2.Exceptions);
13903 Result.Exceptions = ExceptionTypeStorage;
13904 return Result;
13905 }
13906
13907 case EST_Unevaluated:
13908 case EST_Uninstantiated:
13909 case EST_Unparsed:
13910 llvm_unreachable("shouldn't see unresolved exception specifications here");
13911 }
13912
13913 llvm_unreachable("invalid ExceptionSpecificationType");
13914}
13915
13917 Qualifiers &QX, const Type *Y,
13918 Qualifiers &QY) {
13919 Type::TypeClass TC = X->getTypeClass();
13920 assert(TC == Y->getTypeClass());
13921 switch (TC) {
13922#define UNEXPECTED_TYPE(Class, Kind) \
13923 case Type::Class: \
13924 llvm_unreachable("Unexpected " Kind ": " #Class);
13925
13926#define NON_CANONICAL_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "non-canonical")
13927#define TYPE(Class, Base)
13928#include "clang/AST/TypeNodes.inc"
13929
13930#define SUGAR_FREE_TYPE(Class) UNEXPECTED_TYPE(Class, "sugar-free")
13932 SUGAR_FREE_TYPE(DeducedTemplateSpecialization)
13933 SUGAR_FREE_TYPE(DependentBitInt)
13935 SUGAR_FREE_TYPE(ObjCInterface)
13936 SUGAR_FREE_TYPE(SubstTemplateTypeParmPack)
13937 SUGAR_FREE_TYPE(SubstBuiltinTemplatePack)
13938 SUGAR_FREE_TYPE(UnresolvedUsing)
13939 SUGAR_FREE_TYPE(HLSLAttributedResource)
13940 SUGAR_FREE_TYPE(HLSLInlineSpirv)
13941#undef SUGAR_FREE_TYPE
13942#define NON_UNIQUE_TYPE(Class) UNEXPECTED_TYPE(Class, "non-unique")
13943 NON_UNIQUE_TYPE(TypeOfExpr)
13944 NON_UNIQUE_TYPE(VariableArray)
13945#undef NON_UNIQUE_TYPE
13946
13947 UNEXPECTED_TYPE(TypeOf, "sugar")
13948
13949#undef UNEXPECTED_TYPE
13950
13951 case Type::Auto: {
13952 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
13953 assert(AX->getDeducedType().isNull());
13954 assert(AY->getDeducedType().isNull());
13955 assert(AX->getKeyword() == AY->getKeyword());
13956 assert(AX->isInstantiationDependentType() ==
13957 AY->isInstantiationDependentType());
13958 auto As = getCommonTemplateArguments(Ctx, AX->getTypeConstraintArguments(),
13959 AY->getTypeConstraintArguments());
13960 return Ctx.getAutoType(QualType(), AX->getKeyword(),
13962 AX->containsUnexpandedParameterPack(),
13963 getCommonDeclChecked(AX->getTypeConstraintConcept(),
13964 AY->getTypeConstraintConcept()),
13965 As);
13966 }
13967 case Type::IncompleteArray: {
13968 const auto *AX = cast<IncompleteArrayType>(X),
13970 return Ctx.getIncompleteArrayType(
13971 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
13973 }
13974 case Type::DependentSizedArray: {
13975 const auto *AX = cast<DependentSizedArrayType>(X),
13977 return Ctx.getDependentSizedArrayType(
13978 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
13979 getCommonSizeExpr(Ctx, AX, AY), getCommonSizeModifier(AX, AY),
13981 }
13982 case Type::ConstantArray: {
13983 const auto *AX = cast<ConstantArrayType>(X),
13984 *AY = cast<ConstantArrayType>(Y);
13985 assert(AX->getSize() == AY->getSize());
13986 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
13987 ? AX->getSizeExpr()
13988 : nullptr;
13989 return Ctx.getConstantArrayType(
13990 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
13992 }
13993 case Type::ArrayParameter: {
13994 const auto *AX = cast<ArrayParameterType>(X),
13995 *AY = cast<ArrayParameterType>(Y);
13996 assert(AX->getSize() == AY->getSize());
13997 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
13998 ? AX->getSizeExpr()
13999 : nullptr;
14000 auto ArrayTy = Ctx.getConstantArrayType(
14001 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
14003 return Ctx.getArrayParameterType(ArrayTy);
14004 }
14005 case Type::Atomic: {
14006 const auto *AX = cast<AtomicType>(X), *AY = cast<AtomicType>(Y);
14007 return Ctx.getAtomicType(
14008 Ctx.getCommonSugaredType(AX->getValueType(), AY->getValueType()));
14009 }
14010 case Type::Complex: {
14011 const auto *CX = cast<ComplexType>(X), *CY = cast<ComplexType>(Y);
14012 return Ctx.getComplexType(getCommonArrayElementType(Ctx, CX, QX, CY, QY));
14013 }
14014 case Type::Pointer: {
14015 const auto *PX = cast<PointerType>(X), *PY = cast<PointerType>(Y);
14016 return Ctx.getPointerType(getCommonPointeeType(Ctx, PX, PY));
14017 }
14018 case Type::BlockPointer: {
14019 const auto *PX = cast<BlockPointerType>(X), *PY = cast<BlockPointerType>(Y);
14020 return Ctx.getBlockPointerType(getCommonPointeeType(Ctx, PX, PY));
14021 }
14022 case Type::ObjCObjectPointer: {
14023 const auto *PX = cast<ObjCObjectPointerType>(X),
14025 return Ctx.getObjCObjectPointerType(getCommonPointeeType(Ctx, PX, PY));
14026 }
14027 case Type::MemberPointer: {
14028 const auto *PX = cast<MemberPointerType>(X),
14029 *PY = cast<MemberPointerType>(Y);
14030 assert(declaresSameEntity(PX->getMostRecentCXXRecordDecl(),
14031 PY->getMostRecentCXXRecordDecl()));
14032 return Ctx.getMemberPointerType(
14033 getCommonPointeeType(Ctx, PX, PY),
14034 getCommonQualifier(Ctx, PX, PY, /*IsSame=*/true),
14035 PX->getMostRecentCXXRecordDecl());
14036 }
14037 case Type::LValueReference: {
14038 const auto *PX = cast<LValueReferenceType>(X),
14040 // FIXME: Preserve PointeeTypeAsWritten.
14041 return Ctx.getLValueReferenceType(getCommonPointeeType(Ctx, PX, PY),
14042 PX->isSpelledAsLValue() ||
14043 PY->isSpelledAsLValue());
14044 }
14045 case Type::RValueReference: {
14046 const auto *PX = cast<RValueReferenceType>(X),
14048 // FIXME: Preserve PointeeTypeAsWritten.
14049 return Ctx.getRValueReferenceType(getCommonPointeeType(Ctx, PX, PY));
14050 }
14051 case Type::DependentAddressSpace: {
14052 const auto *PX = cast<DependentAddressSpaceType>(X),
14054 assert(Ctx.hasSameExpr(PX->getAddrSpaceExpr(), PY->getAddrSpaceExpr()));
14055 return Ctx.getDependentAddressSpaceType(getCommonPointeeType(Ctx, PX, PY),
14056 PX->getAddrSpaceExpr(),
14057 getCommonAttrLoc(PX, PY));
14058 }
14059 case Type::FunctionNoProto: {
14060 const auto *FX = cast<FunctionNoProtoType>(X),
14062 assert(FX->getExtInfo() == FY->getExtInfo());
14063 return Ctx.getFunctionNoProtoType(
14064 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType()),
14065 FX->getExtInfo());
14066 }
14067 case Type::FunctionProto: {
14068 const auto *FX = cast<FunctionProtoType>(X),
14069 *FY = cast<FunctionProtoType>(Y);
14070 FunctionProtoType::ExtProtoInfo EPIX = FX->getExtProtoInfo(),
14071 EPIY = FY->getExtProtoInfo();
14072 assert(EPIX.ExtInfo == EPIY.ExtInfo);
14073 assert(!EPIX.ExtParameterInfos == !EPIY.ExtParameterInfos);
14074 assert(!EPIX.ExtParameterInfos ||
14075 llvm::equal(
14076 llvm::ArrayRef(EPIX.ExtParameterInfos, FX->getNumParams()),
14077 llvm::ArrayRef(EPIY.ExtParameterInfos, FY->getNumParams())));
14078 assert(EPIX.RefQualifier == EPIY.RefQualifier);
14079 assert(EPIX.TypeQuals == EPIY.TypeQuals);
14080 assert(EPIX.Variadic == EPIY.Variadic);
14081
14082 // FIXME: Can we handle an empty EllipsisLoc?
14083 // Use emtpy EllipsisLoc if X and Y differ.
14084
14085 EPIX.HasTrailingReturn = EPIX.HasTrailingReturn && EPIY.HasTrailingReturn;
14086
14087 QualType R =
14088 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType());
14089 auto P = getCommonTypes(Ctx, FX->param_types(), FY->param_types(),
14090 /*Unqualified=*/true);
14091
14092 SmallVector<QualType, 8> Exceptions;
14094 EPIX.ExceptionSpec, EPIY.ExceptionSpec, Exceptions, true);
14095 return Ctx.getFunctionType(R, P, EPIX);
14096 }
14097 case Type::ObjCObject: {
14098 const auto *OX = cast<ObjCObjectType>(X), *OY = cast<ObjCObjectType>(Y);
14099 assert(
14100 std::equal(OX->getProtocols().begin(), OX->getProtocols().end(),
14101 OY->getProtocols().begin(), OY->getProtocols().end(),
14102 [](const ObjCProtocolDecl *P0, const ObjCProtocolDecl *P1) {
14103 return P0->getCanonicalDecl() == P1->getCanonicalDecl();
14104 }) &&
14105 "protocol lists must be the same");
14106 auto TAs = getCommonTypes(Ctx, OX->getTypeArgsAsWritten(),
14107 OY->getTypeArgsAsWritten());
14108 return Ctx.getObjCObjectType(
14109 Ctx.getCommonSugaredType(OX->getBaseType(), OY->getBaseType()), TAs,
14110 OX->getProtocols(),
14111 OX->isKindOfTypeAsWritten() && OY->isKindOfTypeAsWritten());
14112 }
14113 case Type::ConstantMatrix: {
14114 const auto *MX = cast<ConstantMatrixType>(X),
14115 *MY = cast<ConstantMatrixType>(Y);
14116 assert(MX->getNumRows() == MY->getNumRows());
14117 assert(MX->getNumColumns() == MY->getNumColumns());
14118 return Ctx.getConstantMatrixType(getCommonElementType(Ctx, MX, MY),
14119 MX->getNumRows(), MX->getNumColumns());
14120 }
14121 case Type::DependentSizedMatrix: {
14122 const auto *MX = cast<DependentSizedMatrixType>(X),
14124 assert(Ctx.hasSameExpr(MX->getRowExpr(), MY->getRowExpr()));
14125 assert(Ctx.hasSameExpr(MX->getColumnExpr(), MY->getColumnExpr()));
14126 return Ctx.getDependentSizedMatrixType(
14127 getCommonElementType(Ctx, MX, MY), MX->getRowExpr(),
14128 MX->getColumnExpr(), getCommonAttrLoc(MX, MY));
14129 }
14130 case Type::Vector: {
14131 const auto *VX = cast<VectorType>(X), *VY = cast<VectorType>(Y);
14132 assert(VX->getNumElements() == VY->getNumElements());
14133 assert(VX->getVectorKind() == VY->getVectorKind());
14134 return Ctx.getVectorType(getCommonElementType(Ctx, VX, VY),
14135 VX->getNumElements(), VX->getVectorKind());
14136 }
14137 case Type::ExtVector: {
14138 const auto *VX = cast<ExtVectorType>(X), *VY = cast<ExtVectorType>(Y);
14139 assert(VX->getNumElements() == VY->getNumElements());
14140 return Ctx.getExtVectorType(getCommonElementType(Ctx, VX, VY),
14141 VX->getNumElements());
14142 }
14143 case Type::DependentSizedExtVector: {
14144 const auto *VX = cast<DependentSizedExtVectorType>(X),
14147 getCommonSizeExpr(Ctx, VX, VY),
14148 getCommonAttrLoc(VX, VY));
14149 }
14150 case Type::DependentVector: {
14151 const auto *VX = cast<DependentVectorType>(X),
14153 assert(VX->getVectorKind() == VY->getVectorKind());
14154 return Ctx.getDependentVectorType(
14155 getCommonElementType(Ctx, VX, VY), getCommonSizeExpr(Ctx, VX, VY),
14156 getCommonAttrLoc(VX, VY), VX->getVectorKind());
14157 }
14158 case Type::Enum:
14159 case Type::Record:
14160 case Type::InjectedClassName: {
14161 const auto *TX = cast<TagType>(X), *TY = cast<TagType>(Y);
14162 return Ctx.getTagType(::getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14163 ::getCommonQualifier(Ctx, TX, TY, /*IsSame=*/false),
14164 ::getCommonDeclChecked(TX->getDecl(), TY->getDecl()),
14165 /*OwnedTag=*/false);
14166 }
14167 case Type::TemplateSpecialization: {
14168 const auto *TX = cast<TemplateSpecializationType>(X),
14170 auto As = getCommonTemplateArguments(Ctx, TX->template_arguments(),
14171 TY->template_arguments());
14173 getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14174 ::getCommonTemplateNameChecked(Ctx, TX->getTemplateName(),
14175 TY->getTemplateName(),
14176 /*IgnoreDeduced=*/true),
14177 As, /*CanonicalArgs=*/{}, X->getCanonicalTypeInternal());
14178 }
14179 case Type::Decltype: {
14180 const auto *DX = cast<DecltypeType>(X);
14181 [[maybe_unused]] const auto *DY = cast<DecltypeType>(Y);
14182 assert(DX->isDependentType());
14183 assert(DY->isDependentType());
14184 assert(Ctx.hasSameExpr(DX->getUnderlyingExpr(), DY->getUnderlyingExpr()));
14185 // As Decltype is not uniqued, building a common type would be wasteful.
14186 return QualType(DX, 0);
14187 }
14188 case Type::PackIndexing: {
14189 const auto *DX = cast<PackIndexingType>(X);
14190 [[maybe_unused]] const auto *DY = cast<PackIndexingType>(Y);
14191 assert(DX->isDependentType());
14192 assert(DY->isDependentType());
14193 assert(Ctx.hasSameExpr(DX->getIndexExpr(), DY->getIndexExpr()));
14194 return QualType(DX, 0);
14195 }
14196 case Type::DependentName: {
14197 const auto *NX = cast<DependentNameType>(X),
14198 *NY = cast<DependentNameType>(Y);
14199 assert(NX->getIdentifier() == NY->getIdentifier());
14200 return Ctx.getDependentNameType(
14201 getCommonTypeKeyword(NX, NY, /*IsSame=*/true),
14202 getCommonQualifier(Ctx, NX, NY, /*IsSame=*/true), NX->getIdentifier());
14203 }
14204 case Type::UnaryTransform: {
14205 const auto *TX = cast<UnaryTransformType>(X),
14206 *TY = cast<UnaryTransformType>(Y);
14207 assert(TX->getUTTKind() == TY->getUTTKind());
14208 return Ctx.getUnaryTransformType(
14209 Ctx.getCommonSugaredType(TX->getBaseType(), TY->getBaseType()),
14210 Ctx.getCommonSugaredType(TX->getUnderlyingType(),
14211 TY->getUnderlyingType()),
14212 TX->getUTTKind());
14213 }
14214 case Type::PackExpansion: {
14215 const auto *PX = cast<PackExpansionType>(X),
14216 *PY = cast<PackExpansionType>(Y);
14217 assert(PX->getNumExpansions() == PY->getNumExpansions());
14218 return Ctx.getPackExpansionType(
14219 Ctx.getCommonSugaredType(PX->getPattern(), PY->getPattern()),
14220 PX->getNumExpansions(), false);
14221 }
14222 case Type::Pipe: {
14223 const auto *PX = cast<PipeType>(X), *PY = cast<PipeType>(Y);
14224 assert(PX->isReadOnly() == PY->isReadOnly());
14225 auto MP = PX->isReadOnly() ? &ASTContext::getReadPipeType
14227 return (Ctx.*MP)(getCommonElementType(Ctx, PX, PY));
14228 }
14229 case Type::TemplateTypeParm: {
14230 const auto *TX = cast<TemplateTypeParmType>(X),
14232 assert(TX->getDepth() == TY->getDepth());
14233 assert(TX->getIndex() == TY->getIndex());
14234 assert(TX->isParameterPack() == TY->isParameterPack());
14235 return Ctx.getTemplateTypeParmType(
14236 TX->getDepth(), TX->getIndex(), TX->isParameterPack(),
14237 getCommonDecl(TX->getDecl(), TY->getDecl()));
14238 }
14239 }
14240 llvm_unreachable("Unknown Type Class");
14241}
14242
14244 const Type *Y,
14245 SplitQualType Underlying) {
14246 Type::TypeClass TC = X->getTypeClass();
14247 if (TC != Y->getTypeClass())
14248 return QualType();
14249 switch (TC) {
14250#define UNEXPECTED_TYPE(Class, Kind) \
14251 case Type::Class: \
14252 llvm_unreachable("Unexpected " Kind ": " #Class);
14253#define TYPE(Class, Base)
14254#define DEPENDENT_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "dependent")
14255#include "clang/AST/TypeNodes.inc"
14256
14257#define CANONICAL_TYPE(Class) UNEXPECTED_TYPE(Class, "canonical")
14260 CANONICAL_TYPE(BlockPointer)
14263 CANONICAL_TYPE(ConstantArray)
14264 CANONICAL_TYPE(ArrayParameter)
14265 CANONICAL_TYPE(ConstantMatrix)
14267 CANONICAL_TYPE(ExtVector)
14268 CANONICAL_TYPE(FunctionNoProto)
14269 CANONICAL_TYPE(FunctionProto)
14270 CANONICAL_TYPE(IncompleteArray)
14271 CANONICAL_TYPE(HLSLAttributedResource)
14272 CANONICAL_TYPE(HLSLInlineSpirv)
14273 CANONICAL_TYPE(LValueReference)
14274 CANONICAL_TYPE(ObjCInterface)
14275 CANONICAL_TYPE(ObjCObject)
14276 CANONICAL_TYPE(ObjCObjectPointer)
14280 CANONICAL_TYPE(RValueReference)
14281 CANONICAL_TYPE(VariableArray)
14283#undef CANONICAL_TYPE
14284
14285#undef UNEXPECTED_TYPE
14286
14287 case Type::Adjusted: {
14288 const auto *AX = cast<AdjustedType>(X), *AY = cast<AdjustedType>(Y);
14289 QualType OX = AX->getOriginalType(), OY = AY->getOriginalType();
14290 if (!Ctx.hasSameType(OX, OY))
14291 return QualType();
14292 // FIXME: It's inefficient to have to unify the original types.
14293 return Ctx.getAdjustedType(Ctx.getCommonSugaredType(OX, OY),
14294 Ctx.getQualifiedType(Underlying));
14295 }
14296 case Type::Decayed: {
14297 const auto *DX = cast<DecayedType>(X), *DY = cast<DecayedType>(Y);
14298 QualType OX = DX->getOriginalType(), OY = DY->getOriginalType();
14299 if (!Ctx.hasSameType(OX, OY))
14300 return QualType();
14301 // FIXME: It's inefficient to have to unify the original types.
14302 return Ctx.getDecayedType(Ctx.getCommonSugaredType(OX, OY),
14303 Ctx.getQualifiedType(Underlying));
14304 }
14305 case Type::Attributed: {
14306 const auto *AX = cast<AttributedType>(X), *AY = cast<AttributedType>(Y);
14307 AttributedType::Kind Kind = AX->getAttrKind();
14308 if (Kind != AY->getAttrKind())
14309 return QualType();
14310 QualType MX = AX->getModifiedType(), MY = AY->getModifiedType();
14311 if (!Ctx.hasSameType(MX, MY))
14312 return QualType();
14313 // FIXME: It's inefficient to have to unify the modified types.
14314 return Ctx.getAttributedType(Kind, Ctx.getCommonSugaredType(MX, MY),
14315 Ctx.getQualifiedType(Underlying),
14316 AX->getAttr());
14317 }
14318 case Type::BTFTagAttributed: {
14319 const auto *BX = cast<BTFTagAttributedType>(X);
14320 const BTFTypeTagAttr *AX = BX->getAttr();
14321 // The attribute is not uniqued, so just compare the tag.
14322 if (AX->getBTFTypeTag() !=
14323 cast<BTFTagAttributedType>(Y)->getAttr()->getBTFTypeTag())
14324 return QualType();
14325 return Ctx.getBTFTagAttributedType(AX, Ctx.getQualifiedType(Underlying));
14326 }
14327 case Type::Auto: {
14328 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
14329
14330 AutoTypeKeyword KW = AX->getKeyword();
14331 if (KW != AY->getKeyword())
14332 return QualType();
14333
14334 TemplateDecl *CD = ::getCommonDecl(AX->getTypeConstraintConcept(),
14335 AY->getTypeConstraintConcept());
14337 if (CD &&
14338 getCommonTemplateArguments(Ctx, As, AX->getTypeConstraintArguments(),
14339 AY->getTypeConstraintArguments())) {
14340 CD = nullptr; // The arguments differ, so make it unconstrained.
14341 As.clear();
14342 }
14343
14344 // Both auto types can't be dependent, otherwise they wouldn't have been
14345 // sugar. This implies they can't contain unexpanded packs either.
14346 return Ctx.getAutoType(Ctx.getQualifiedType(Underlying), AX->getKeyword(),
14347 /*IsDependent=*/false, /*IsPack=*/false, CD, As);
14348 }
14349 case Type::PackIndexing:
14350 case Type::Decltype:
14351 return QualType();
14352 case Type::DeducedTemplateSpecialization:
14353 // FIXME: Try to merge these.
14354 return QualType();
14355 case Type::MacroQualified: {
14356 const auto *MX = cast<MacroQualifiedType>(X),
14357 *MY = cast<MacroQualifiedType>(Y);
14358 const IdentifierInfo *IX = MX->getMacroIdentifier();
14359 if (IX != MY->getMacroIdentifier())
14360 return QualType();
14361 return Ctx.getMacroQualifiedType(Ctx.getQualifiedType(Underlying), IX);
14362 }
14363 case Type::SubstTemplateTypeParm: {
14364 const auto *SX = cast<SubstTemplateTypeParmType>(X),
14366 Decl *CD =
14367 ::getCommonDecl(SX->getAssociatedDecl(), SY->getAssociatedDecl());
14368 if (!CD)
14369 return QualType();
14370 unsigned Index = SX->getIndex();
14371 if (Index != SY->getIndex())
14372 return QualType();
14373 auto PackIndex = SX->getPackIndex();
14374 if (PackIndex != SY->getPackIndex())
14375 return QualType();
14376 return Ctx.getSubstTemplateTypeParmType(Ctx.getQualifiedType(Underlying),
14377 CD, Index, PackIndex,
14378 SX->getFinal() && SY->getFinal());
14379 }
14380 case Type::ObjCTypeParam:
14381 // FIXME: Try to merge these.
14382 return QualType();
14383 case Type::Paren:
14384 return Ctx.getParenType(Ctx.getQualifiedType(Underlying));
14385
14386 case Type::TemplateSpecialization: {
14387 const auto *TX = cast<TemplateSpecializationType>(X),
14389 TemplateName CTN =
14390 ::getCommonTemplateName(Ctx, TX->getTemplateName(),
14391 TY->getTemplateName(), /*IgnoreDeduced=*/true);
14392 if (!CTN.getAsVoidPointer())
14393 return QualType();
14395 if (getCommonTemplateArguments(Ctx, As, TX->template_arguments(),
14396 TY->template_arguments()))
14397 return QualType();
14399 getCommonTypeKeyword(TX, TY, /*IsSame=*/false), CTN, As,
14400 /*CanonicalArgs=*/{}, Ctx.getQualifiedType(Underlying));
14401 }
14402 case Type::Typedef: {
14403 const auto *TX = cast<TypedefType>(X), *TY = cast<TypedefType>(Y);
14404 const TypedefNameDecl *CD = ::getCommonDecl(TX->getDecl(), TY->getDecl());
14405 if (!CD)
14406 return QualType();
14407 return Ctx.getTypedefType(
14408 ::getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14409 ::getCommonQualifier(Ctx, TX, TY, /*IsSame=*/false), CD,
14410 Ctx.getQualifiedType(Underlying));
14411 }
14412 case Type::TypeOf: {
14413 // The common sugar between two typeof expressions, where one is
14414 // potentially a typeof_unqual and the other is not, we unify to the
14415 // qualified type as that retains the most information along with the type.
14416 // We only return a typeof_unqual type when both types are unqual types.
14421 return Ctx.getTypeOfType(Ctx.getQualifiedType(Underlying), Kind);
14422 }
14423 case Type::TypeOfExpr:
14424 return QualType();
14425
14426 case Type::UnaryTransform: {
14427 const auto *UX = cast<UnaryTransformType>(X),
14428 *UY = cast<UnaryTransformType>(Y);
14429 UnaryTransformType::UTTKind KX = UX->getUTTKind();
14430 if (KX != UY->getUTTKind())
14431 return QualType();
14432 QualType BX = UX->getBaseType(), BY = UY->getBaseType();
14433 if (!Ctx.hasSameType(BX, BY))
14434 return QualType();
14435 // FIXME: It's inefficient to have to unify the base types.
14436 return Ctx.getUnaryTransformType(Ctx.getCommonSugaredType(BX, BY),
14437 Ctx.getQualifiedType(Underlying), KX);
14438 }
14439 case Type::Using: {
14440 const auto *UX = cast<UsingType>(X), *UY = cast<UsingType>(Y);
14441 const UsingShadowDecl *CD = ::getCommonDecl(UX->getDecl(), UY->getDecl());
14442 if (!CD)
14443 return QualType();
14444 return Ctx.getUsingType(::getCommonTypeKeyword(UX, UY, /*IsSame=*/false),
14445 ::getCommonQualifier(Ctx, UX, UY, /*IsSame=*/false),
14446 CD, Ctx.getQualifiedType(Underlying));
14447 }
14448 case Type::MemberPointer: {
14449 const auto *PX = cast<MemberPointerType>(X),
14450 *PY = cast<MemberPointerType>(Y);
14451 CXXRecordDecl *Cls = PX->getMostRecentCXXRecordDecl();
14452 assert(Cls == PY->getMostRecentCXXRecordDecl());
14453 return Ctx.getMemberPointerType(
14454 ::getCommonPointeeType(Ctx, PX, PY),
14455 ::getCommonQualifier(Ctx, PX, PY, /*IsSame=*/false), Cls);
14456 }
14457 case Type::CountAttributed: {
14458 const auto *DX = cast<CountAttributedType>(X),
14460 if (DX->isCountInBytes() != DY->isCountInBytes())
14461 return QualType();
14462 if (DX->isOrNull() != DY->isOrNull())
14463 return QualType();
14464 Expr *CEX = DX->getCountExpr();
14465 Expr *CEY = DY->getCountExpr();
14466 ArrayRef<clang::TypeCoupledDeclRefInfo> CDX = DX->getCoupledDecls();
14467 if (Ctx.hasSameExpr(CEX, CEY))
14468 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX,
14469 DX->isCountInBytes(), DX->isOrNull(),
14470 CDX);
14471 if (!CEX->isIntegerConstantExpr(Ctx) || !CEY->isIntegerConstantExpr(Ctx))
14472 return QualType();
14473 // Two declarations with the same integer constant may still differ in their
14474 // expression pointers, so we need to evaluate them.
14475 llvm::APSInt VX = *CEX->getIntegerConstantExpr(Ctx);
14476 llvm::APSInt VY = *CEY->getIntegerConstantExpr(Ctx);
14477 if (VX != VY)
14478 return QualType();
14479 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX,
14480 DX->isCountInBytes(), DX->isOrNull(),
14481 CDX);
14482 }
14483 case Type::PredefinedSugar:
14484 assert(cast<PredefinedSugarType>(X)->getKind() !=
14486 return QualType();
14487 }
14488 llvm_unreachable("Unhandled Type Class");
14489}
14490
14491static auto unwrapSugar(SplitQualType &T, Qualifiers &QTotal) {
14493 while (true) {
14494 QTotal.addConsistentQualifiers(T.Quals);
14495 QualType NT = T.Ty->getLocallyUnqualifiedSingleStepDesugaredType();
14496 if (NT == QualType(T.Ty, 0))
14497 break;
14498 R.push_back(T);
14499 T = NT.split();
14500 }
14501 return R;
14502}
14503
14505 bool Unqualified) const {
14506 assert(Unqualified ? hasSameUnqualifiedType(X, Y) : hasSameType(X, Y));
14507 if (X == Y)
14508 return X;
14509 if (!Unqualified) {
14510 if (X.isCanonical())
14511 return X;
14512 if (Y.isCanonical())
14513 return Y;
14514 }
14515
14516 SplitQualType SX = X.split(), SY = Y.split();
14517 Qualifiers QX, QY;
14518 // Desugar SX and SY, setting the sugar and qualifiers aside into Xs and Ys,
14519 // until we reach their underlying "canonical nodes". Note these are not
14520 // necessarily canonical types, as they may still have sugared properties.
14521 // QX and QY will store the sum of all qualifiers in Xs and Ys respectively.
14522 auto Xs = ::unwrapSugar(SX, QX), Ys = ::unwrapSugar(SY, QY);
14523
14524 // If this is an ArrayType, the element qualifiers are interchangeable with
14525 // the top level qualifiers.
14526 // * In case the canonical nodes are the same, the elements types are already
14527 // the same.
14528 // * Otherwise, the element types will be made the same, and any different
14529 // element qualifiers will be moved up to the top level qualifiers, per
14530 // 'getCommonArrayElementType'.
14531 // In both cases, this means there may be top level qualifiers which differ
14532 // between X and Y. If so, these differing qualifiers are redundant with the
14533 // element qualifiers, and can be removed without changing the canonical type.
14534 // The desired behaviour is the same as for the 'Unqualified' case here:
14535 // treat the redundant qualifiers as sugar, remove the ones which are not
14536 // common to both sides.
14537 bool KeepCommonQualifiers = Unqualified || isa<ArrayType>(SX.Ty);
14538
14539 if (SX.Ty != SY.Ty) {
14540 // The canonical nodes differ. Build a common canonical node out of the two,
14541 // unifying their sugar. This may recurse back here.
14542 SX.Ty =
14543 ::getCommonNonSugarTypeNode(*this, SX.Ty, QX, SY.Ty, QY).getTypePtr();
14544 } else {
14545 // The canonical nodes were identical: We may have desugared too much.
14546 // Add any common sugar back in.
14547 while (!Xs.empty() && !Ys.empty() && Xs.back().Ty == Ys.back().Ty) {
14548 QX -= SX.Quals;
14549 QY -= SY.Quals;
14550 SX = Xs.pop_back_val();
14551 SY = Ys.pop_back_val();
14552 }
14553 }
14554 if (KeepCommonQualifiers)
14556 else
14557 assert(QX == QY);
14558
14559 // Even though the remaining sugar nodes in Xs and Ys differ, some may be
14560 // related. Walk up these nodes, unifying them and adding the result.
14561 while (!Xs.empty() && !Ys.empty()) {
14562 auto Underlying = SplitQualType(
14563 SX.Ty, Qualifiers::removeCommonQualifiers(SX.Quals, SY.Quals));
14564 SX = Xs.pop_back_val();
14565 SY = Ys.pop_back_val();
14566 SX.Ty = ::getCommonSugarTypeNode(*this, SX.Ty, SY.Ty, Underlying)
14568 // Stop at the first pair which is unrelated.
14569 if (!SX.Ty) {
14570 SX.Ty = Underlying.Ty;
14571 break;
14572 }
14573 QX -= Underlying.Quals;
14574 };
14575
14576 // Add back the missing accumulated qualifiers, which were stripped off
14577 // with the sugar nodes we could not unify.
14578 QualType R = getQualifiedType(SX.Ty, QX);
14579 assert(Unqualified ? hasSameUnqualifiedType(R, X) : hasSameType(R, X));
14580 return R;
14581}
14582
14584 assert(Ty->isFixedPointType());
14585
14587 return Ty;
14588
14589 switch (Ty->castAs<BuiltinType>()->getKind()) {
14590 default:
14591 llvm_unreachable("Not a saturated fixed point type!");
14592 case BuiltinType::SatShortAccum:
14593 return ShortAccumTy;
14594 case BuiltinType::SatAccum:
14595 return AccumTy;
14596 case BuiltinType::SatLongAccum:
14597 return LongAccumTy;
14598 case BuiltinType::SatUShortAccum:
14599 return UnsignedShortAccumTy;
14600 case BuiltinType::SatUAccum:
14601 return UnsignedAccumTy;
14602 case BuiltinType::SatULongAccum:
14603 return UnsignedLongAccumTy;
14604 case BuiltinType::SatShortFract:
14605 return ShortFractTy;
14606 case BuiltinType::SatFract:
14607 return FractTy;
14608 case BuiltinType::SatLongFract:
14609 return LongFractTy;
14610 case BuiltinType::SatUShortFract:
14611 return UnsignedShortFractTy;
14612 case BuiltinType::SatUFract:
14613 return UnsignedFractTy;
14614 case BuiltinType::SatULongFract:
14615 return UnsignedLongFractTy;
14616 }
14617}
14618
14620 assert(Ty->isFixedPointType());
14621
14622 if (Ty->isSaturatedFixedPointType()) return Ty;
14623
14624 switch (Ty->castAs<BuiltinType>()->getKind()) {
14625 default:
14626 llvm_unreachable("Not a fixed point type!");
14627 case BuiltinType::ShortAccum:
14628 return SatShortAccumTy;
14629 case BuiltinType::Accum:
14630 return SatAccumTy;
14631 case BuiltinType::LongAccum:
14632 return SatLongAccumTy;
14633 case BuiltinType::UShortAccum:
14635 case BuiltinType::UAccum:
14636 return SatUnsignedAccumTy;
14637 case BuiltinType::ULongAccum:
14639 case BuiltinType::ShortFract:
14640 return SatShortFractTy;
14641 case BuiltinType::Fract:
14642 return SatFractTy;
14643 case BuiltinType::LongFract:
14644 return SatLongFractTy;
14645 case BuiltinType::UShortFract:
14647 case BuiltinType::UFract:
14648 return SatUnsignedFractTy;
14649 case BuiltinType::ULongFract:
14651 }
14652}
14653
14655 if (LangOpts.OpenCL)
14657
14658 if (LangOpts.CUDA)
14660
14661 return getLangASFromTargetAS(AS);
14662}
14663
14664// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
14665// doesn't include ASTContext.h
14666template
14668 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
14670 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
14671 const clang::ASTContext &Ctx, Decl *Value);
14672
14674 assert(Ty->isFixedPointType());
14675
14676 const TargetInfo &Target = getTargetInfo();
14677 switch (Ty->castAs<BuiltinType>()->getKind()) {
14678 default:
14679 llvm_unreachable("Not a fixed point type!");
14680 case BuiltinType::ShortAccum:
14681 case BuiltinType::SatShortAccum:
14682 return Target.getShortAccumScale();
14683 case BuiltinType::Accum:
14684 case BuiltinType::SatAccum:
14685 return Target.getAccumScale();
14686 case BuiltinType::LongAccum:
14687 case BuiltinType::SatLongAccum:
14688 return Target.getLongAccumScale();
14689 case BuiltinType::UShortAccum:
14690 case BuiltinType::SatUShortAccum:
14691 return Target.getUnsignedShortAccumScale();
14692 case BuiltinType::UAccum:
14693 case BuiltinType::SatUAccum:
14694 return Target.getUnsignedAccumScale();
14695 case BuiltinType::ULongAccum:
14696 case BuiltinType::SatULongAccum:
14697 return Target.getUnsignedLongAccumScale();
14698 case BuiltinType::ShortFract:
14699 case BuiltinType::SatShortFract:
14700 return Target.getShortFractScale();
14701 case BuiltinType::Fract:
14702 case BuiltinType::SatFract:
14703 return Target.getFractScale();
14704 case BuiltinType::LongFract:
14705 case BuiltinType::SatLongFract:
14706 return Target.getLongFractScale();
14707 case BuiltinType::UShortFract:
14708 case BuiltinType::SatUShortFract:
14709 return Target.getUnsignedShortFractScale();
14710 case BuiltinType::UFract:
14711 case BuiltinType::SatUFract:
14712 return Target.getUnsignedFractScale();
14713 case BuiltinType::ULongFract:
14714 case BuiltinType::SatULongFract:
14715 return Target.getUnsignedLongFractScale();
14716 }
14717}
14718
14720 assert(Ty->isFixedPointType());
14721
14722 const TargetInfo &Target = getTargetInfo();
14723 switch (Ty->castAs<BuiltinType>()->getKind()) {
14724 default:
14725 llvm_unreachable("Not a fixed point type!");
14726 case BuiltinType::ShortAccum:
14727 case BuiltinType::SatShortAccum:
14728 return Target.getShortAccumIBits();
14729 case BuiltinType::Accum:
14730 case BuiltinType::SatAccum:
14731 return Target.getAccumIBits();
14732 case BuiltinType::LongAccum:
14733 case BuiltinType::SatLongAccum:
14734 return Target.getLongAccumIBits();
14735 case BuiltinType::UShortAccum:
14736 case BuiltinType::SatUShortAccum:
14737 return Target.getUnsignedShortAccumIBits();
14738 case BuiltinType::UAccum:
14739 case BuiltinType::SatUAccum:
14740 return Target.getUnsignedAccumIBits();
14741 case BuiltinType::ULongAccum:
14742 case BuiltinType::SatULongAccum:
14743 return Target.getUnsignedLongAccumIBits();
14744 case BuiltinType::ShortFract:
14745 case BuiltinType::SatShortFract:
14746 case BuiltinType::Fract:
14747 case BuiltinType::SatFract:
14748 case BuiltinType::LongFract:
14749 case BuiltinType::SatLongFract:
14750 case BuiltinType::UShortFract:
14751 case BuiltinType::SatUShortFract:
14752 case BuiltinType::UFract:
14753 case BuiltinType::SatUFract:
14754 case BuiltinType::ULongFract:
14755 case BuiltinType::SatULongFract:
14756 return 0;
14757 }
14758}
14759
14760llvm::FixedPointSemantics
14762 assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
14763 "Can only get the fixed point semantics for a "
14764 "fixed point or integer type.");
14765 if (Ty->isIntegerType())
14766 return llvm::FixedPointSemantics::GetIntegerSemantics(
14767 getIntWidth(Ty), Ty->isSignedIntegerType());
14768
14769 bool isSigned = Ty->isSignedFixedPointType();
14770 return llvm::FixedPointSemantics(
14771 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
14773 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
14774}
14775
14776llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
14777 assert(Ty->isFixedPointType());
14778 return llvm::APFixedPoint::getMax(getFixedPointSemantics(Ty));
14779}
14780
14781llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
14782 assert(Ty->isFixedPointType());
14783 return llvm::APFixedPoint::getMin(getFixedPointSemantics(Ty));
14784}
14785
14787 assert(Ty->isUnsignedFixedPointType() &&
14788 "Expected unsigned fixed point type");
14789
14790 switch (Ty->castAs<BuiltinType>()->getKind()) {
14791 case BuiltinType::UShortAccum:
14792 return ShortAccumTy;
14793 case BuiltinType::UAccum:
14794 return AccumTy;
14795 case BuiltinType::ULongAccum:
14796 return LongAccumTy;
14797 case BuiltinType::SatUShortAccum:
14798 return SatShortAccumTy;
14799 case BuiltinType::SatUAccum:
14800 return SatAccumTy;
14801 case BuiltinType::SatULongAccum:
14802 return SatLongAccumTy;
14803 case BuiltinType::UShortFract:
14804 return ShortFractTy;
14805 case BuiltinType::UFract:
14806 return FractTy;
14807 case BuiltinType::ULongFract:
14808 return LongFractTy;
14809 case BuiltinType::SatUShortFract:
14810 return SatShortFractTy;
14811 case BuiltinType::SatUFract:
14812 return SatFractTy;
14813 case BuiltinType::SatULongFract:
14814 return SatLongFractTy;
14815 default:
14816 llvm_unreachable("Unexpected unsigned fixed point type");
14817 }
14818}
14819
14820// Given a list of FMV features, return a concatenated list of the
14821// corresponding backend features (which may contain duplicates).
14822static std::vector<std::string> getFMVBackendFeaturesFor(
14823 const llvm::SmallVectorImpl<StringRef> &FMVFeatStrings) {
14824 std::vector<std::string> BackendFeats;
14825 llvm::AArch64::ExtensionSet FeatureBits;
14826 for (StringRef F : FMVFeatStrings)
14827 if (auto FMVExt = llvm::AArch64::parseFMVExtension(F))
14828 if (FMVExt->ID)
14829 FeatureBits.enable(*FMVExt->ID);
14830 FeatureBits.toLLVMFeatureList(BackendFeats);
14831 return BackendFeats;
14832}
14833
14834ParsedTargetAttr
14835ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const {
14836 assert(TD != nullptr);
14837 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(TD->getFeaturesStr());
14838
14839 llvm::erase_if(ParsedAttr.Features, [&](const std::string &Feat) {
14840 return !Target->isValidFeatureName(StringRef{Feat}.substr(1));
14841 });
14842 return ParsedAttr;
14843}
14844
14845void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
14846 const FunctionDecl *FD) const {
14847 if (FD)
14848 getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD));
14849 else
14850 Target->initFeatureMap(FeatureMap, getDiagnostics(),
14851 Target->getTargetOpts().CPU,
14852 Target->getTargetOpts().Features);
14853}
14854
14855// Fills in the supplied string map with the set of target features for the
14856// passed in function.
14857void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
14858 GlobalDecl GD) const {
14859 StringRef TargetCPU = Target->getTargetOpts().CPU;
14860 const FunctionDecl *FD = GD.getDecl()->getAsFunction();
14861 if (const auto *TD = FD->getAttr<TargetAttr>()) {
14863
14864 // Make a copy of the features as passed on the command line into the
14865 // beginning of the additional features from the function to override.
14866 // AArch64 handles command line option features in parseTargetAttr().
14867 if (!Target->getTriple().isAArch64())
14868 ParsedAttr.Features.insert(
14869 ParsedAttr.Features.begin(),
14870 Target->getTargetOpts().FeaturesAsWritten.begin(),
14871 Target->getTargetOpts().FeaturesAsWritten.end());
14872
14873 if (ParsedAttr.CPU != "" && Target->isValidCPUName(ParsedAttr.CPU))
14874 TargetCPU = ParsedAttr.CPU;
14875
14876 // Now populate the feature map, first with the TargetCPU which is either
14877 // the default or a new one from the target attribute string. Then we'll use
14878 // the passed in features (FeaturesAsWritten) along with the new ones from
14879 // the attribute.
14880 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU,
14881 ParsedAttr.Features);
14882 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
14884 Target->getCPUSpecificCPUDispatchFeatures(
14885 SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp);
14886 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
14887 Features.insert(Features.begin(),
14888 Target->getTargetOpts().FeaturesAsWritten.begin(),
14889 Target->getTargetOpts().FeaturesAsWritten.end());
14890 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14891 } else if (const auto *TC = FD->getAttr<TargetClonesAttr>()) {
14892 if (Target->getTriple().isAArch64()) {
14894 TC->getFeatures(Feats, GD.getMultiVersionIndex());
14895 std::vector<std::string> Features = getFMVBackendFeaturesFor(Feats);
14896 Features.insert(Features.begin(),
14897 Target->getTargetOpts().FeaturesAsWritten.begin(),
14898 Target->getTargetOpts().FeaturesAsWritten.end());
14899 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14900 } else if (Target->getTriple().isRISCV()) {
14901 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
14902 std::vector<std::string> Features;
14903 if (VersionStr != "default") {
14904 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(VersionStr);
14905 Features.insert(Features.begin(), ParsedAttr.Features.begin(),
14906 ParsedAttr.Features.end());
14907 }
14908 Features.insert(Features.begin(),
14909 Target->getTargetOpts().FeaturesAsWritten.begin(),
14910 Target->getTargetOpts().FeaturesAsWritten.end());
14911 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14912 } else {
14913 std::vector<std::string> Features;
14914 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
14915 if (VersionStr.starts_with("arch="))
14916 TargetCPU = VersionStr.drop_front(sizeof("arch=") - 1);
14917 else if (VersionStr != "default")
14918 Features.push_back((StringRef{"+"} + VersionStr).str());
14919 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14920 }
14921 } else if (const auto *TV = FD->getAttr<TargetVersionAttr>()) {
14922 std::vector<std::string> Features;
14923 if (Target->getTriple().isRISCV()) {
14924 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(TV->getName());
14925 Features.insert(Features.begin(), ParsedAttr.Features.begin(),
14926 ParsedAttr.Features.end());
14927 } else {
14928 assert(Target->getTriple().isAArch64());
14930 TV->getFeatures(Feats);
14931 Features = getFMVBackendFeaturesFor(Feats);
14932 }
14933 Features.insert(Features.begin(),
14934 Target->getTargetOpts().FeaturesAsWritten.begin(),
14935 Target->getTargetOpts().FeaturesAsWritten.end());
14936 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14937 } else {
14938 FeatureMap = Target->getTargetOpts().FeatureMap;
14939 }
14940}
14941
14943 CanQualType KernelNameType,
14944 const FunctionDecl *FD) {
14945 // Host and device compilation may use different ABIs and different ABIs
14946 // may allocate name mangling discriminators differently. A discriminator
14947 // override is used to ensure consistent discriminator allocation across
14948 // host and device compilation.
14949 auto DeviceDiscriminatorOverrider =
14950 [](ASTContext &Ctx, const NamedDecl *ND) -> UnsignedOrNone {
14951 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
14952 if (RD->isLambda())
14953 return RD->getDeviceLambdaManglingNumber();
14954 return std::nullopt;
14955 };
14956 std::unique_ptr<MangleContext> MC{ItaniumMangleContext::create(
14957 Context, Context.getDiagnostics(), DeviceDiscriminatorOverrider)};
14958
14959 // Construct a mangled name for the SYCL kernel caller offload entry point.
14960 // FIXME: The Itanium typeinfo mangling (_ZTS<type>) is currently used to
14961 // name the SYCL kernel caller offload entry point function. This mangling
14962 // does not suffice to clearly identify symbols that correspond to SYCL
14963 // kernel caller functions, nor is this mangling natural for targets that
14964 // use a non-Itanium ABI.
14965 std::string Buffer;
14966 Buffer.reserve(128);
14967 llvm::raw_string_ostream Out(Buffer);
14968 MC->mangleCanonicalTypeName(KernelNameType, Out);
14969 std::string KernelName = Out.str();
14970
14971 return {KernelNameType, FD, KernelName};
14972}
14973
14975 // If the function declaration to register is invalid or dependent, the
14976 // registration attempt is ignored.
14977 if (FD->isInvalidDecl() || FD->isTemplated())
14978 return;
14979
14980 const auto *SKEPAttr = FD->getAttr<SYCLKernelEntryPointAttr>();
14981 assert(SKEPAttr && "Missing sycl_kernel_entry_point attribute");
14982
14983 // Be tolerant of multiple registration attempts so long as each attempt
14984 // is for the same entity. Callers are obligated to detect and diagnose
14985 // conflicting kernel names prior to calling this function.
14986 CanQualType KernelNameType = getCanonicalType(SKEPAttr->getKernelName());
14987 auto IT = SYCLKernels.find(KernelNameType);
14988 assert((IT == SYCLKernels.end() ||
14989 declaresSameEntity(FD, IT->second.getKernelEntryPointDecl())) &&
14990 "SYCL kernel name conflict");
14991 (void)IT;
14992 SYCLKernels.insert(std::make_pair(
14993 KernelNameType, BuildSYCLKernelInfo(*this, KernelNameType, FD)));
14994}
14995
14997 CanQualType KernelNameType = getCanonicalType(T);
14998 return SYCLKernels.at(KernelNameType);
14999}
15000
15002 CanQualType KernelNameType = getCanonicalType(T);
15003 auto IT = SYCLKernels.find(KernelNameType);
15004 if (IT != SYCLKernels.end())
15005 return &IT->second;
15006 return nullptr;
15007}
15008
15010 OMPTraitInfoVector.emplace_back(new OMPTraitInfo());
15011 return *OMPTraitInfoVector.back();
15012}
15013
15016 const ASTContext::SectionInfo &Section) {
15017 if (Section.Decl)
15018 return DB << Section.Decl;
15019 return DB << "a prior #pragma section";
15020}
15021
15022bool ASTContext::mayExternalize(const Decl *D) const {
15023 bool IsInternalVar =
15024 isa<VarDecl>(D) &&
15026 bool IsExplicitDeviceVar = (D->hasAttr<CUDADeviceAttr>() &&
15027 !D->getAttr<CUDADeviceAttr>()->isImplicit()) ||
15028 (D->hasAttr<CUDAConstantAttr>() &&
15029 !D->getAttr<CUDAConstantAttr>()->isImplicit());
15030 // CUDA/HIP: managed variables need to be externalized since it is
15031 // a declaration in IR, therefore cannot have internal linkage. Kernels in
15032 // anonymous name space needs to be externalized to avoid duplicate symbols.
15033 return (IsInternalVar &&
15034 (D->hasAttr<HIPManagedAttr>() || IsExplicitDeviceVar)) ||
15035 (D->hasAttr<CUDAGlobalAttr>() &&
15037 GVA_Internal);
15038}
15039
15041 return mayExternalize(D) &&
15042 (D->hasAttr<HIPManagedAttr>() || D->hasAttr<CUDAGlobalAttr>() ||
15044}
15045
15046StringRef ASTContext::getCUIDHash() const {
15047 if (!CUIDHash.empty())
15048 return CUIDHash;
15049 if (LangOpts.CUID.empty())
15050 return StringRef();
15051 CUIDHash = llvm::utohexstr(llvm::MD5Hash(LangOpts.CUID), /*LowerCase=*/true);
15052 return CUIDHash;
15053}
15054
15055const CXXRecordDecl *
15057 assert(ThisClass);
15058 assert(ThisClass->isPolymorphic());
15059 const CXXRecordDecl *PrimaryBase = ThisClass;
15060 while (1) {
15061 assert(PrimaryBase);
15062 assert(PrimaryBase->isPolymorphic());
15063 auto &Layout = getASTRecordLayout(PrimaryBase);
15064 auto Base = Layout.getPrimaryBase();
15065 if (!Base || Base == PrimaryBase || !Base->isPolymorphic())
15066 break;
15067 PrimaryBase = Base;
15068 }
15069 return PrimaryBase;
15070}
15071
15073 StringRef MangledName) {
15074 auto *Method = cast<CXXMethodDecl>(VirtualMethodDecl.getDecl());
15075 assert(Method->isVirtual());
15076 bool DefaultIncludesPointerAuth =
15077 LangOpts.PointerAuthCalls || LangOpts.PointerAuthIntrinsics;
15078
15079 if (!DefaultIncludesPointerAuth)
15080 return true;
15081
15082 auto Existing = ThunksToBeAbbreviated.find(VirtualMethodDecl);
15083 if (Existing != ThunksToBeAbbreviated.end())
15084 return Existing->second.contains(MangledName.str());
15085
15086 std::unique_ptr<MangleContext> Mangler(createMangleContext());
15087 llvm::StringMap<llvm::SmallVector<std::string, 2>> Thunks;
15088 auto VtableContext = getVTableContext();
15089 if (const auto *ThunkInfos = VtableContext->getThunkInfo(VirtualMethodDecl)) {
15090 auto *Destructor = dyn_cast<CXXDestructorDecl>(Method);
15091 for (const auto &Thunk : *ThunkInfos) {
15092 SmallString<256> ElidedName;
15093 llvm::raw_svector_ostream ElidedNameStream(ElidedName);
15094 if (Destructor)
15095 Mangler->mangleCXXDtorThunk(Destructor, VirtualMethodDecl.getDtorType(),
15096 Thunk, /* elideOverrideInfo */ true,
15097 ElidedNameStream);
15098 else
15099 Mangler->mangleThunk(Method, Thunk, /* elideOverrideInfo */ true,
15100 ElidedNameStream);
15101 SmallString<256> MangledName;
15102 llvm::raw_svector_ostream mangledNameStream(MangledName);
15103 if (Destructor)
15104 Mangler->mangleCXXDtorThunk(Destructor, VirtualMethodDecl.getDtorType(),
15105 Thunk, /* elideOverrideInfo */ false,
15106 mangledNameStream);
15107 else
15108 Mangler->mangleThunk(Method, Thunk, /* elideOverrideInfo */ false,
15109 mangledNameStream);
15110
15111 Thunks[ElidedName].push_back(std::string(MangledName));
15112 }
15113 }
15114 llvm::StringSet<> SimplifiedThunkNames;
15115 for (auto &ThunkList : Thunks) {
15116 llvm::sort(ThunkList.second);
15117 SimplifiedThunkNames.insert(ThunkList.second[0]);
15118 }
15119 bool Result = SimplifiedThunkNames.contains(MangledName);
15120 ThunksToBeAbbreviated[VirtualMethodDecl] = std::move(SimplifiedThunkNames);
15121 return Result;
15122}
This file provides AST data structures related to concepts.
static void SortAndUniqueProtocols(SmallVectorImpl< ObjCProtocolDecl * > &Protocols)
static bool isCanonicalExceptionSpecification(const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType)
static SourceLocation getCommonAttrLoc(const T *X, const T *Y)
static auto getCanonicalTemplateArguments(const ASTContext &C, ArrayRef< TemplateArgument > Args, bool &AnyNonCanonArgs)
static char getObjCEncodingForPrimitiveType(const ASTContext *C, const BuiltinType *BT)
static bool isSameQualifier(const NestedNameSpecifier X, const NestedNameSpecifier Y)
static bool unionHasUniqueObjectRepresentations(const ASTContext &Context, const RecordDecl *RD, bool CheckIfTriviallyCopyable)
static TypedefDecl * CreateHexagonBuiltinVaListDecl(const ASTContext *Context)
#define CANONICAL_TYPE(Class)
static ElaboratedTypeKeyword getCommonTypeKeyword(const T *X, const T *Y, bool IsSame)
static Decl * getCommonDecl(Decl *X, Decl *Y)
static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context, const Decl *D, GVALinkage L)
static bool isTypeTypedefedAsBOOL(QualType T)
static void EncodeBitField(const ASTContext *Ctx, std::string &S, QualType T, const FieldDecl *FD)
static GVALinkage basicGVALinkageForVariable(const ASTContext &Context, const VarDecl *VD)
static const TemplateArgument * getDefaultTemplateArgumentOrNone(const NamedDecl *P)
static QualType getCommonArrayElementType(const ASTContext &Ctx, const T *X, Qualifiers &QX, const T *Y, Qualifiers &QY)
#define SUGAR_FREE_TYPE(Class)
static SYCLKernelInfo BuildSYCLKernelInfo(ASTContext &Context, CanQualType KernelNameType, const FunctionDecl *FD)
static bool hasTemplateSpecializationInEncodedString(const Type *T, bool VisitBasesAndFields)
static void getIntersectionOfProtocols(ASTContext &Context, const ObjCInterfaceDecl *CommonBase, const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT, SmallVectorImpl< ObjCProtocolDecl * > &IntersectionSet)
getIntersectionOfProtocols - This routine finds the intersection of set of protocols inherited from t...
static bool areCompatMatrixTypes(const ConstantMatrixType *LHS, const ConstantMatrixType *RHS)
areCompatMatrixTypes - Return true if the two specified matrix types are compatible.
static TypedefDecl * CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context)
static bool sameObjCTypeArgs(ASTContext &ctx, const ObjCInterfaceDecl *iface, ArrayRef< QualType > lhsArgs, ArrayRef< QualType > rhsArgs, bool stripKindOf)
static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs, QualType rhs)
Determine whether the first type is a subtype of the second.
static const Type * getIntegerTypeForEnum(const EnumType *ET)
static bool hasSameCudaAttrs(const FunctionDecl *A, const FunctionDecl *B)
static TemplateName getCommonTemplateName(const ASTContext &Ctx, TemplateName X, TemplateName Y, bool IgnoreDeduced=false)
static int CmpProtocolNames(ObjCProtocolDecl *const *LHS, ObjCProtocolDecl *const *RHS)
CmpProtocolNames - Comparison predicate for sorting protocols alphabetically.
static auto * getCommonSizeExpr(const ASTContext &Ctx, T *X, T *Y)
static TypedefDecl * CreatePowerABIBuiltinVaListDecl(const ASTContext *Context)
static auto getCommonSizeModifier(const ArrayType *X, const ArrayType *Y)
static TemplateArgument getCommonTemplateArgument(const ASTContext &Ctx, const TemplateArgument &X, const TemplateArgument &Y)
static std::optional< int64_t > structHasUniqueObjectRepresentations(const ASTContext &Context, const RecordDecl *RD, bool CheckIfTriviallyCopyable)
static bool hasSameOverloadableAttrs(const FunctionDecl *A, const FunctionDecl *B)
Determine whether the attributes we can overload on are identical for A and B.
static T * getCommonDeclChecked(T *X, T *Y)
static NestedNameSpecifier getCommonNNS(const ASTContext &Ctx, NestedNameSpecifier NNS1, NestedNameSpecifier NNS2, bool IsSame)
Returns a NestedNameSpecifier which has only the common sugar present in both NNS1 and NNS2.
static TypedefDecl * CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context)
static int64_t getSubobjectOffset(const FieldDecl *Field, const ASTContext &Context, const clang::ASTRecordLayout &)
static QualType getCommonSugarTypeNode(const ASTContext &Ctx, const Type *X, const Type *Y, SplitQualType Underlying)
static TypedefDecl * CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context)
static QualType getCommonNonSugarTypeNode(const ASTContext &Ctx, const Type *X, Qualifiers &QX, const Type *Y, Qualifiers &QY)
static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET, QualType other, bool isBlockReturnType)
Given that we have an enum type and a non-enum type, try to merge them.
static GVALinkage adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D, GVALinkage L)
Adjust the GVALinkage for a declaration based on what an external AST source knows about whether ther...
static TypedefDecl * CreateSystemZBuiltinVaListDecl(const ASTContext *Context)
static std::optional< int64_t > getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context, bool CheckIfTriviallyCopyable)
static GVALinkage basicGVALinkageForFunction(const ASTContext &Context, const FunctionDecl *FD)
#define NON_UNIQUE_TYPE(Class)
static TypedefDecl * CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context)
static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI, const LangOptions &LangOpts)
static ElaboratedTypeKeyword getCanonicalElaboratedTypeKeyword(ElaboratedTypeKeyword Keyword)
static QualType getCommonPointeeType(const ASTContext &Ctx, const T *X, const T *Y)
static auto getCommonIndexTypeCVRQualifiers(const ArrayType *X, const ArrayType *Y)
static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context, ASTContext::GetBuiltinTypeError &Error, bool &RequiresICE, bool AllowTypeModifiers)
DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the pointer over the consume...
FloatingRank
@ FloatRank
@ LongDoubleRank
@ Float16Rank
@ Ibm128Rank
@ Float128Rank
@ BFloat16Rank
@ HalfRank
@ DoubleRank
static TypedefDecl * CreateCharPtrBuiltinVaListDecl(const ASTContext *Context)
static bool areSortedAndUniqued(ArrayRef< ObjCProtocolDecl * > Protocols)
static TypeInfoChars getConstantArrayInfoInChars(const ASTContext &Context, const ConstantArrayType *CAT)
getConstantArrayInfoInChars - Performing the computation in CharUnits instead of in bits prevents ove...
static FloatingRank getFloatingRank(QualType T)
getFloatingRank - Return a relative rank for floating point types.
static bool getCommonTemplateArguments(const ASTContext &Ctx, SmallVectorImpl< TemplateArgument > &R, ArrayRef< TemplateArgument > Xs, ArrayRef< TemplateArgument > Ys)
static TypedefDecl * CreateXtensaABIBuiltinVaListDecl(const ASTContext *Context)
static QualType getCommonElementType(const ASTContext &Ctx, const T *X, const T *Y)
static void mergeTypeLists(const ASTContext &Ctx, SmallVectorImpl< QualType > &Out, ArrayRef< QualType > X, ArrayRef< QualType > Y)
static void encodeTypeForFunctionPointerAuth(const ASTContext &Ctx, raw_ostream &OS, QualType QT)
Encode a function type for use in the discriminator of a function pointer type.
static std::optional< int64_t > structSubobjectsHaveUniqueObjectRepresentations(const RangeT &Subobjects, int64_t CurOffsetInBits, const ASTContext &Context, const clang::ASTRecordLayout &Layout, bool CheckIfTriviallyCopyable)
static uint64_t getRVVTypeSize(ASTContext &Context, const BuiltinType *Ty)
getRVVTypeSize - Return RVV vector register size.
static auto unwrapSugar(SplitQualType &T, Qualifiers &QTotal)
static TemplateName getCommonTemplateNameChecked(const ASTContext &Ctx, TemplateName X, TemplateName Y, bool IgnoreDeduced)
static int compareObjCProtocolsByName(ObjCProtocolDecl *const *lhs, ObjCProtocolDecl *const *rhs)
Comparison routine for Objective-C protocols to be used with llvm::array_pod_sort.
static std::string charUnitsToString(const CharUnits &CU)
static const TagDecl * getNonInjectedClassName(const TagDecl *TD)
static bool hasAnyPackExpansions(ArrayRef< TemplateArgument > Args)
static char ObjCEncodingForEnumDecl(const ASTContext *C, const EnumDecl *ED)
static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod, SmallVectorImpl< const NamedDecl * > &Redeclared)
static SmallVector< SourceLocation, 2 > getDeclLocsForCommentSearch(const Decl *D, SourceManager &SourceMgr)
static auto getCommonTypes(const ASTContext &Ctx, ArrayRef< QualType > Xs, ArrayRef< QualType > Ys, bool Unqualified=false)
static bool isCanonicalResultType(QualType T)
Determine whether T is canonical as the result type of a function.
static TypedefDecl * CreateMSVaListDecl(const ASTContext *Context)
static bool areCompatVectorTypes(const VectorType *LHS, const VectorType *RHS)
areCompatVectorTypes - Return true if the two specified vector types are compatible.
static TypedefDecl * CreateCharPtrNamedVaListDecl(const ASTContext *Context, StringRef Name)
static NestedNameSpecifier getCommonQualifier(const ASTContext &Ctx, const T *X, const T *Y, bool IsSame)
#define UNEXPECTED_TYPE(Class, Kind)
static TypedefDecl * CreateVaListDecl(const ASTContext *Context, TargetInfo::BuiltinVaListKind Kind)
static bool primaryBaseHaseAddressDiscriminatedVTableAuthentication(const ASTContext &Context, const CXXRecordDecl *Class)
static std::vector< std::string > getFMVBackendFeaturesFor(const llvm::SmallVectorImpl< StringRef > &FMVFeatStrings)
Defines the clang::ASTContext interface.
#define V(N, I)
#define BuiltinTemplate(BTName)
Definition ASTContext.h:451
Provides definitions for the various language-specific address spaces.
static bool isUnsigned(SValBuilder &SVB, NonLoc Value)
Defines enum values for all the target-independent builtin functions.
static bool CanThrow(Expr *E, ASTContext &Ctx)
Definition CFG.cpp:2777
Defines the clang::CommentOptions interface.
static Decl::Kind getKind(const Decl *D)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
This file defines OpenMP nodes for declarative directives.
Defines the C++ template declaration subclasses.
Defines the ExceptionSpecificationType enumeration and various utility functions.
Defines the clang::Expr interface and subclasses for C++ expressions.
FormatToken * Next
The next token in the unwrapped line.
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
static const Decl * getCanonicalDecl(const Decl *D)
#define X(type, name)
Definition Value.h:97
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::LangOptions interface.
llvm::MachO::Record Record
Definition MachO.h:31
static bool hasFeature(StringRef Feature, const LangOptions &LangOpts, const TargetInfo &Target)
Determine whether a translation unit built using the current language options has the given feature.
Definition Module.cpp:95
Defines the clang::Module class, which describes a module in the source code.
Defines types useful for describing an Objective-C runtime.
#define SM(sm)
static bool compare(const PathDiagnostic &X, const PathDiagnostic &Y)
static QualType getUnderlyingType(const SubRegion *R)
Defines the clang::SourceLocation class and associated facilities.
Defines the SourceManager interface.
Defines various enumerations that describe declaration and type specifiers.
static QualType getPointeeType(const MemRegion *R)
Defines the TargetCXXABI class, which abstracts details of the C++ ABI that we're targeting.
Defines the clang::TypeLoc interface and its subclasses.
C Language Family Type Representation.
__device__ __2f16 float c
QualType getReadPipeType(QualType T) const
Return a read_only pipe type for the specified type.
QualType getWritePipeType(QualType T) const
Return a write_only pipe type for the specified type.
@ GE_Missing_stdio
Missing a type from <stdio.h>
@ GE_Missing_ucontext
Missing a type from <ucontext.h>
@ GE_Missing_setjmp
Missing a type from <setjmp.h>
RawComment * getRawCommentForDeclNoCacheImpl(const Decl *D, const SourceLocation RepresentativeLocForDecl, const std::map< unsigned, RawComment * > &CommentsInFile) const
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
bool isMemberPointerToDerivedMember() const
Definition APValue.cpp:1073
const ValueDecl * getMemberPointerDecl() const
Definition APValue.cpp:1066
ArrayRef< const CXXRecordDecl * > getMemberPointerPath() const
Definition APValue.cpp:1080
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:220
bool getByrefLifetime(QualType Ty, Qualifiers::ObjCLifetime &Lifetime, bool &HasByrefExtendedLayout) const
Returns true, if given type has a known lifetime.
MSGuidDecl * getMSGuidDecl(MSGuidDeclParts Parts) const
Return a declaration for the global GUID object representing the given GUID value.
CanQualType AccumTy
BuiltinVectorTypeInfo getBuiltinVectorTypeInfo(const BuiltinType *VecTy) const
Returns the element type, element count and number of vectors (in case of tuple) for a builtin vector...
bool ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl, const ObjCMethodDecl *MethodImp)
CanQualType ObjCBuiltinSelTy
TranslationUnitDecl * getTranslationUnitDecl() const
const ConstantArrayType * getAsConstantArrayType(QualType T) const
CanQualType getCanonicalFunctionResultType(QualType ResultType) const
Adjust the given function result type.
QualType getAtomicType(QualType T) const
Return the uniqued reference to the atomic type for the specified type.
LangAS getOpenCLTypeAddrSpace(const Type *T) const
Get address space for OpenCL type.
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
void InitBuiltinTypes(const TargetInfo &Target, const TargetInfo *AuxTarget=nullptr)
Initialize built-in types.
ParentMapContext & getParentMapContext()
Returns the dynamic AST node parent map context.
QualType getParenType(QualType NamedType) const
size_t getSideTableAllocatedMemory() const
Return the total memory used for various side tables.
MemberSpecializationInfo * getInstantiatedFromStaticDataMember(const VarDecl *Var)
If this variable is an instantiated static data member of a class template specialization,...
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type.
CanQualType ARCUnbridgedCastTy
QualType getDependentSizedMatrixType(QualType ElementType, Expr *RowExpr, Expr *ColumnExpr, SourceLocation AttrLoc) const
Return the unique reference to the matrix type of the specified element type and size.
QualType getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr, QualType Wrapped) const
llvm::DenseMap< const Decl *, comments::FullComment * > ParsedComments
Mapping from declarations to parsed comments attached to any redeclaration.
Definition ASTContext.h:988
unsigned getManglingNumber(const NamedDecl *ND, bool ForAuxTarget=false) const
CanQualType LongTy
unsigned getIntWidth(QualType T) const
CanQualType getCanonicalParamType(QualType T) const
Return the canonical parameter type corresponding to the specific potentially non-canonical one.
const FunctionType * adjustFunctionType(const FunctionType *Fn, FunctionType::ExtInfo EInfo)
Change the ExtInfo on a function type.
TemplateOrSpecializationInfo getTemplateOrSpecializationInfo(const VarDecl *Var)
CanQualType WIntTy
@ Weak
Weak definition of inline variable.
@ WeakUnknown
Weak for now, might become strong later in this TU.
void setObjCConstantStringInterface(ObjCInterfaceDecl *Decl)
TypedefDecl * getObjCClassDecl() const
Retrieve the typedef declaration corresponding to the predefined Objective-C 'Class' type.
TypedefNameDecl * getTypedefNameForUnnamedTagDecl(const TagDecl *TD)
TypedefDecl * getCFConstantStringDecl() const
CanQualType Int128Ty
CanQualType SatUnsignedFractTy
void setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern)
Remember that the using decl Inst is an instantiation of the using decl Pattern of a class template.
bool areCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given types are an RISC-V vector builtin type and a VectorType that is a fixed-len...
ExternCContextDecl * getExternCContextDecl() const
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
ParsedTargetAttr filterFunctionTargetAttrs(const TargetAttr *TD) const
Parses the target attributes passed in, and returns only the ones that are valid feature names.
QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT)
TypedefDecl * getObjCSelDecl() const
Retrieve the typedef corresponding to the predefined 'SEL' type in Objective-C.
CanQualType UnsignedShortAccumTy
TypedefDecl * getObjCInstanceTypeDecl()
Retrieve the typedef declaration corresponding to the Objective-C "instancetype" type.
QualType adjustFunctionResultType(QualType FunctionType, QualType NewResultType)
Change the result type of a function type, preserving sugar such as attributed types.
void setTemplateOrSpecializationInfo(VarDecl *Inst, TemplateOrSpecializationInfo TSI)
bool isTypeAwareOperatorNewOrDelete(const FunctionDecl *FD) const
bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto, ObjCProtocolDecl *rProto) const
ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the inheritance hierarchy of 'rProto...
TypedefDecl * buildImplicitTypedef(QualType T, StringRef Name) const
Create a new implicit TU-level typedef declaration.
QualType getCanonicalTemplateSpecializationType(ElaboratedTypeKeyword Keyword, TemplateName T, ArrayRef< TemplateArgument > CanonicalArgs) const
QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl, ObjCInterfaceDecl *PrevDecl=nullptr) const
getObjCInterfaceType - Return the unique reference to the type for the specified ObjC interface decl.
void adjustObjCTypeParamBoundType(const ObjCTypeParamDecl *Orig, ObjCTypeParamDecl *New) const
QualType getBlockPointerType(QualType T) const
Return the uniqued reference to the type for a block of the specified type.
TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg) const
Retrieve the "canonical" template argument.
QualType getAutoRRefDeductType() const
C++11 deduction pattern for 'auto &&' type.
TypedefDecl * getBuiltinMSVaListDecl() const
Retrieve the C type declaration corresponding to the predefined __builtin_ms_va_list type.
bool ObjCQualifiedIdTypesAreCompatible(const ObjCObjectPointerType *LHS, const ObjCObjectPointerType *RHS, bool ForCompare)
ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an ObjCQualifiedIDType.
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:776
comments::FullComment * cloneFullComment(comments::FullComment *FC, const Decl *D) const
CharUnits getObjCEncodingTypeSize(QualType T) const
Return the size of type T for Objective-C encoding purpose, in characters.
int getIntegerTypeOrder(QualType LHS, QualType RHS) const
Return the highest ranked integer type, see C99 6.3.1.8p1.
QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType, const Attr *attr=nullptr) const
TypedefDecl * getObjCIdDecl() const
Retrieve the typedef corresponding to the predefined id type in Objective-C.
void setCurrentNamedModule(Module *M)
Set the (C++20) module we are building.
QualType getProcessIDType() const
Return the unique type for "pid_t" defined in <sys/types.h>.
CharUnits getMemberPointerPathAdjustment(const APValue &MP) const
Find the 'this' offset for the member path in a pointer-to-member APValue.
bool mayExternalize(const Decl *D) const
Whether a C++ static variable or CUDA/HIP kernel may be externalized.
std::unique_ptr< MangleNumberingContext > createMangleNumberingContext() const
CanQualType SatAccumTy
QualType getUnsignedPointerDiffType() const
Return the unique unsigned counterpart of "ptrdiff_t" integer type.
QualType getScalableVectorType(QualType EltTy, unsigned NumElts, unsigned NumFields=1) const
Return the unique reference to a scalable vector type of the specified element type and scalable numb...
bool hasSameExpr(const Expr *X, const Expr *Y) const
Determine whether the given expressions X and Y are equivalent.
void getObjCEncodingForType(QualType T, std::string &S, const FieldDecl *Field=nullptr, QualType *NotEncodedT=nullptr) const
Emit the Objective-CC type encoding for the given type T into S.
MangleContext * createMangleContext(const TargetInfo *T=nullptr)
If T is null pointer, assume the target in ASTContext.
QualType getRealTypeForBitwidth(unsigned DestWidth, FloatModeKind ExplicitType) const
getRealTypeForBitwidth - sets floating point QualTy according to specified bitwidth.
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like 'int()'.
CanQualType ShortAccumTy
ASTMutationListener * getASTMutationListener() const
Retrieve a pointer to the AST mutation listener associated with this AST context, if any.
unsigned NumImplicitCopyAssignmentOperatorsDeclared
The number of implicitly-declared copy assignment operators for which declarations were built.
uint64_t getTargetNullPointerValue(QualType QT) const
Get target-dependent integer value for null pointer which is used for constant folding.
unsigned getTypeUnadjustedAlign(QualType T) const
Return the ABI-specified natural alignment of a (complete) type T, before alignment adjustments,...
unsigned char getFixedPointIBits(QualType Ty) const
QualType getSubstBuiltinTemplatePack(const TemplateArgument &ArgPack)
QualType getCorrespondingSignedFixedPointType(QualType Ty) const
IntrusiveRefCntPtr< ExternalASTSource > ExternalSource
Definition ASTContext.h:777
CanQualType FloatTy
QualType getArrayParameterType(QualType Ty) const
Return the uniqued reference to a specified array parameter type from the original array type.
QualType getCountAttributedType(QualType T, Expr *CountExpr, bool CountInBytes, bool OrNull, ArrayRef< TypeCoupledDeclRefInfo > DependentDecls) const
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
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)
overridden_method_range overridden_methods(const CXXMethodDecl *Method) const
void setIsTypeAwareOperatorNewOrDelete(const FunctionDecl *FD, bool IsTypeAware)
QualType getDependentBitIntType(bool Unsigned, Expr *BitsExpr) const
Return a dependent bit-precise integer type with the specified signedness and bit count.
void setObjCImplementation(ObjCInterfaceDecl *IFaceD, ObjCImplementationDecl *ImplD)
Set the implementation of ObjCInterfaceDecl.
StringRef getCUIDHash() const
bool isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const
Returns true if this is an inline-initialized static data member which is treated as a definition for...
bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT)
canAssignObjCInterfaces - Return true if the two interface types are compatible for assignment from R...
CanQualType VoidPtrTy
QualType getReferenceQualifiedType(const Expr *e) const
getReferenceQualifiedType - Given an expr, will return the type for that expression,...
bool hasSameFunctionTypeIgnoringExceptionSpec(QualType T, QualType U) const
Determine whether two function types are the same, ignoring exception specifications in cases where t...
QualType getBlockDescriptorExtendedType() const
Gets the struct used to keep track of the extended descriptor for pointer to blocks.
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
CanQualType DependentTy
bool QIdProtocolsAdoptObjCObjectProtocols(QualType QT, ObjCInterfaceDecl *IDecl)
QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in QT's qualified-id protocol list adopt...
FunctionProtoType::ExceptionSpecInfo mergeExceptionSpecs(FunctionProtoType::ExceptionSpecInfo ESI1, FunctionProtoType::ExceptionSpecInfo ESI2, SmallVectorImpl< QualType > &ExceptionTypeStorage, bool AcceptDependent) const
void addLazyModuleInitializers(Module *M, ArrayRef< GlobalDeclID > IDs)
bool isSameConstraintExpr(const Expr *XCE, const Expr *YCE) const
Determine whether two 'requires' expressions are similar enough that they may be used in re-declarati...
bool BlockRequiresCopying(QualType Ty, const VarDecl *D)
Returns true iff we need copy/dispose helpers for the given type.
CanQualType NullPtrTy
QualType getUsingType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const UsingShadowDecl *D, QualType UnderlyingType=QualType()) const
CanQualType WideCharTy
CanQualType OMPIteratorTy
IdentifierTable & Idents
Definition ASTContext.h:772
Builtin::Context & BuiltinInfo
Definition ASTContext.h:774
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
void addModuleInitializer(Module *M, Decl *Init)
Add a declaration to the list of declarations that are initialized for a module.
const LangOptions & getLangOpts() const
Definition ASTContext.h:926
QualType getFunctionTypeWithoutPtrSizes(QualType T)
Get a function type and produce the equivalent function type where pointer size address spaces in the...
uint64_t lookupFieldBitOffset(const ObjCInterfaceDecl *OID, const ObjCIvarDecl *Ivar) const
Get the offset of an ObjCIvarDecl in bits.
SelectorTable & Selectors
Definition ASTContext.h:773
bool isTypeIgnoredBySanitizer(const SanitizerMask &Mask, const QualType &Ty) const
Check if a type can have its sanitizer instrumentation elided based on its presence within an ignorel...
unsigned getMinGlobalAlignOfVar(uint64_t Size, const VarDecl *VD) const
Return the minimum alignment as specified by the target.
RawCommentList Comments
All comments in this translation unit.
Definition ASTContext.h:959
bool isSameDefaultTemplateArgument(const NamedDecl *X, const NamedDecl *Y) const
Determine whether two default template arguments are similar enough that they may be used in declarat...
QualType applyObjCProtocolQualifiers(QualType type, ArrayRef< ObjCProtocolDecl * > protocols, bool &hasError, bool allowOnPointerType=false) const
Apply Objective-C protocol qualifiers to the given type.
QualType getMacroQualifiedType(QualType UnderlyingTy, const IdentifierInfo *MacroII) const
QualType removePtrSizeAddrSpace(QualType T) const
Remove the existing address space on the type if it is a pointer size address space and return the ty...
bool areLaxCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible RISC-V vector types as defined by -flax-vect...
CanQualType SatShortFractTy
QualType getDecayedType(QualType T) const
Return the uniqued reference to the decayed version of the given type.
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod) const
Retrieves the default calling convention for the current context.
bool canBindObjCObjectType(QualType To, QualType From)
TemplateTemplateParmDecl * insertCanonicalTemplateTemplateParmDeclInternal(TemplateTemplateParmDecl *CanonTTP) const
int getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const
Compare the rank of two floating point types as above, but compare equal if both types have the same ...
QualType getUIntPtrType() const
Return a type compatible with "uintptr_t" (C99 7.18.1.4), as defined by the target.
void setParameterIndex(const ParmVarDecl *D, unsigned index)
Used by ParmVarDecl to store on the side the index of the parameter when it exceeds the size of the n...
QualType getFunctionTypeWithExceptionSpec(QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const
Get a function type and produce the equivalent function type with the specified exception specificati...
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier NNS, const IdentifierInfo *Name) const
Qualifiers::GC getObjCGCAttrKind(QualType Ty) const
Return one of the GCNone, Weak or Strong Objective-C garbage collection attributes.
CanQualType Ibm128Ty
bool hasUniqueObjectRepresentations(QualType Ty, bool CheckIfTriviallyCopyable=true) const
Return true if the specified type has unique object representations according to (C++17 [meta....
CanQualType getCanonicalSizeType() const
bool typesAreBlockPointerCompatible(QualType, QualType)
CanQualType SatUnsignedAccumTy
bool useAbbreviatedThunkName(GlobalDecl VirtualMethodDecl, StringRef MangledName)
const ASTRecordLayout & getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const
Get or compute information about the layout of the specified Objective-C interface.
void forEachMultiversionedFunctionVersion(const FunctionDecl *FD, llvm::function_ref< void(FunctionDecl *)> Pred) const
Visits all versions of a multiversioned function with the passed predicate.
void setInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst, UsingEnumDecl *Pattern)
Remember that the using enum decl Inst is an instantiation of the using enum decl Pattern of a class ...
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
QualType getSignatureParameterType(QualType T) const
Retrieve the parameter type as adjusted for use in the signature of a function, decaying array and fu...
CanQualType ArraySectionTy
CanQualType ObjCBuiltinIdTy
overridden_cxx_method_iterator overridden_methods_end(const CXXMethodDecl *Method) const
VTableContextBase * getVTableContext()
ComparisonCategories CompCategories
Types and expressions required to build C++2a three-way comparisons using operator<=>,...
int getFloatingTypeOrder(QualType LHS, QualType RHS) const
Compare the rank of the two specified floating point types, ignoring the domain of the type (i....
unsigned CountNonClassIvars(const ObjCInterfaceDecl *OI) const
ObjCPropertyImplDecl * getObjCPropertyImplDeclForPropertyDecl(const ObjCPropertyDecl *PD, const Decl *Container) const
bool isNearlyEmpty(const CXXRecordDecl *RD) const
PointerAuthQualifier getObjCMemberSelTypePtrAuth()
QualType AutoDeductTy
CanQualType BoolTy
void cacheRawCommentForDecl(const Decl &OriginalD, const RawComment &Comment) const
Attaches Comment to OriginalD and to its redeclaration chain and removes the redeclaration chain from...
void attachCommentsToJustParsedDecls(ArrayRef< Decl * > Decls, const Preprocessor *PP)
Searches existing comments for doc comments that should be attached to Decls.
QualType getIntTypeForBitwidth(unsigned DestWidth, unsigned Signed) const
getIntTypeForBitwidth - sets integer QualTy according to specified details: bitwidth,...
void setStaticLocalNumber(const VarDecl *VD, unsigned Number)
QualType getCFConstantStringType() const
Return the C structure type used to represent constant CFStrings.
void eraseDeclAttrs(const Decl *D)
Erase the attributes corresponding to the given declaration.
UsingEnumDecl * getInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst)
If the given using-enum decl Inst is an instantiation of another using-enum decl, return it.
RecordDecl * getCFConstantStringTagDecl() const
std::string getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const
Emit the encoded type for the function Decl into S.
TypeSourceInfo * getTemplateSpecializationTypeInfo(ElaboratedTypeKeyword Keyword, SourceLocation ElaboratedKeywordLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKeywordLoc, TemplateName T, SourceLocation TLoc, const TemplateArgumentListInfo &SpecifiedArgs, ArrayRef< TemplateArgument > CanonicalArgs, QualType Canon=QualType()) const
QualType getTemplateTypeParmType(unsigned Depth, unsigned Index, bool ParameterPack, TemplateTypeParmDecl *ParmDecl=nullptr) const
Retrieve the template type parameter type for a template parameter or parameter pack with the given d...
CanQualType UnsignedFractTy
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
QualType mergeFunctionParameterTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false)
mergeFunctionParameterTypes - merge two types which appear as function parameter types
void addOverriddenMethod(const CXXMethodDecl *Method, const CXXMethodDecl *Overridden)
Note that the given C++ Method overrides the given Overridden method.
TemplateTemplateParmDecl * findCanonicalTemplateTemplateParmDeclInternal(TemplateTemplateParmDecl *TTP) const
CanQualType Float128Ty
CanQualType ObjCBuiltinClassTy
unsigned NumImplicitDefaultConstructorsDeclared
The number of implicitly-declared default constructors for which declarations were built.
CanQualType UnresolvedTemplateTy
OMPTraitInfo & getNewOMPTraitInfo()
Return a new OMPTraitInfo object owned by this context.
friend class CXXRecordDecl
Definition ASTContext.h:555
CanQualType UnsignedLongTy
void DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, bool leafClass, SmallVectorImpl< const ObjCIvarDecl * > &Ivars) const
DeepCollectObjCIvars - This routine first collects all declared, but not synthesized,...
bool computeBestEnumTypes(bool IsPacked, unsigned NumNegativeBits, unsigned NumPositiveBits, QualType &BestType, QualType &BestPromotionType)
Compute BestType and BestPromotionType for an enum based on the highest number of negative and positi...
llvm::APFixedPoint getFixedPointMin(QualType Ty) const
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
QualType adjustType(QualType OldType, llvm::function_ref< QualType(QualType)> Adjust) const
Rebuild a type, preserving any existing type sugar.
void addedLocalImportDecl(ImportDecl *Import)
Notify the AST context that a new import declaration has been parsed or implicitly created within thi...
const TranslationUnitKind TUKind
Definition ASTContext.h:775
CanQualType UnsignedLongAccumTy
QualType AutoRRefDeductTy
TypeInfo getTypeInfo(const Type *T) const
Get the size and alignment of the specified complete type in bits.
CanQualType ShortFractTy
QualType getStringLiteralArrayType(QualType EltTy, unsigned Length) const
Return a type for a constant array for a string literal of the specified element type and length.
QualType getCorrespondingSaturatedType(QualType Ty) const
bool isSameEntity(const NamedDecl *X, const NamedDecl *Y) const
Determine whether the two declarations refer to the same entity.
QualType getSubstTemplateTypeParmPackType(Decl *AssociatedDecl, unsigned Index, bool Final, const TemplateArgument &ArgPack)
CanQualType BoundMemberTy
CanQualType SatUnsignedShortFractTy
CanQualType CharTy
QualType removeAddrSpaceQualType(QualType T) const
Remove any existing address space on the type and returns the type with qualifiers intact (or that's ...
bool hasSameFunctionTypeIgnoringParamABI(QualType T, QualType U) const
Determine if two function types are the same, ignoring parameter ABI annotations.
TypedefDecl * getInt128Decl() const
Retrieve the declaration for the 128-bit signed integer type.
unsigned getOpenMPDefaultSimdAlign(QualType T) const
Get default simd alignment of the specified complete type in bits.
QualType getObjCSuperType() const
Returns the C struct type for objc_super.
QualType getBlockDescriptorType() const
Gets the struct used to keep track of the descriptor for pointer to blocks.
bool CommentsLoaded
True if comments are already loaded from ExternalASTSource.
Definition ASTContext.h:962
BlockVarCopyInit getBlockVarCopyInit(const VarDecl *VD) const
Get the copy initialization expression of the VarDecl VD, or nullptr if none exists.
QualType getHLSLInlineSpirvType(uint32_t Opcode, uint32_t Size, uint32_t Alignment, ArrayRef< SpirvOperand > Operands)
unsigned NumImplicitMoveConstructorsDeclared
The number of implicitly-declared move constructors for which declarations were built.
bool isInSameModule(const Module *M1, const Module *M2) const
If the two module M1 and M2 are in the same module.
unsigned NumImplicitCopyConstructorsDeclared
The number of implicitly-declared copy constructors for which declarations were built.
CanQualType IntTy
llvm::DenseSet< const VarDecl * > CUDADeviceVarODRUsedByHost
Keep track of CUDA/HIP device-side variables ODR-used by host code.
CanQualType PseudoObjectTy
QualType getWebAssemblyExternrefType() const
Return a WebAssembly externref type.
void setTraversalScope(const std::vector< Decl * > &)
CharUnits getTypeUnadjustedAlignInChars(QualType T) const
getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a type, in characters,...
QualType getAdjustedType(QualType Orig, QualType New) const
Return the uniqued reference to a type adjusted from the original type to a new type.
friend class NestedNameSpecifier
Definition ASTContext.h:221
void PrintStats() const
unsigned getAlignOfGlobalVar(QualType T, const VarDecl *VD) const
Return the alignment in bits that should be given to a global variable with type T.
TypeInfoChars getTypeInfoDataSizeInChars(QualType T) const
MangleNumberingContext & getManglingNumberContext(const DeclContext *DC)
Retrieve the context for computing mangling numbers in the given DeclContext.
comments::FullComment * getLocalCommentForDeclUncached(const Decl *D) const
Return parsed documentation comment attached to a given declaration.
unsigned NumImplicitDestructors
The number of implicitly-declared destructors.
CanQualType Float16Ty
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
bool isAlignmentRequired(const Type *T) const
Determine if the alignment the type has was required using an alignment attribute.
TagDecl * MSGuidTagDecl
bool areComparableObjCPointerTypes(QualType LHS, QualType RHS)
MangleContext * createDeviceMangleContext(const TargetInfo &T)
Creates a device mangle context to correctly mangle lambdas in a mixed architecture compile by settin...
CharUnits getExnObjectAlignment() const
Return the alignment (in bytes) of the thrown exception object.
CanQualType SignedCharTy
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
ASTMutationListener * Listener
Definition ASTContext.h:778
CanQualType ObjCBuiltinBoolTy
TypeInfoChars getTypeInfoInChars(const Type *T) const
QualType getPredefinedSugarType(PredefinedSugarType::Kind KD) const
QualType getObjCObjectType(QualType Base, ObjCProtocolDecl *const *Protocols, unsigned NumProtocols) const
Legacy interface: cannot provide type arguments or __kindof.
TemplateParamObjectDecl * getTemplateParamObjectDecl(QualType T, const APValue &V) const
Return the template parameter object of the given type with the given value.
CanQualType OverloadTy
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
int64_t toBits(CharUnits CharSize) const
Convert a size in characters to a size in bits.
TemplateTemplateParmDecl * getCanonicalTemplateTemplateParmDecl(TemplateTemplateParmDecl *TTP) const
Canonicalize the given TemplateTemplateParmDecl.
CanQualType OCLClkEventTy
void adjustExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI, bool AsWritten=false)
Change the exception specification on a function once it is delay-parsed, instantiated,...
TypedefDecl * getUInt128Decl() const
Retrieve the declaration for the 128-bit unsigned integer type.
const clang::PrintingPolicy & getPrintingPolicy() const
Definition ASTContext.h:825
void ResetObjCLayout(const ObjCInterfaceDecl *D)
ArrayRef< Module * > getModulesWithMergedDefinition(const NamedDecl *Def)
Get the additional modules in which the definition Def has been merged.
llvm::FixedPointSemantics getFixedPointSemantics(QualType Ty) const
CanQualType SatUnsignedShortAccumTy
QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false, bool BlockReturnType=false, bool IsConditionalOperator=false)
const RawComment * getRawCommentForAnyRedecl(const Decl *D, const Decl **OriginalDecl=nullptr) const
Return the documentation comment attached to a given declaration.
CharUnits getAlignOfGlobalVarInChars(QualType T, const VarDecl *VD) const
Return the alignment in characters that should be given to a global variable with type T.
const ObjCMethodDecl * getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const
Get the duplicate declaration of a ObjCMethod in the same interface, or null if none exists.
QualType getPackIndexingType(QualType Pattern, Expr *IndexExpr, bool FullySubstituted=false, ArrayRef< QualType > Expansions={}, UnsignedOrNone Index=std::nullopt) const
static bool isObjCNSObjectType(QualType Ty)
Return true if this is an NSObject object with its NSObject attribute set.
GVALinkage GetGVALinkageForVariable(const VarDecl *VD) const
llvm::PointerUnion< VarTemplateDecl *, MemberSpecializationInfo * > TemplateOrSpecializationInfo
A type synonym for the TemplateOrInstantiation mapping.
Definition ASTContext.h:547
UsingShadowDecl * getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst)
QualType getVariableArrayType(QualType EltTy, Expr *NumElts, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return a non-unique reference to the type for a variable array of the specified element type.
QualType getObjCIdType() const
Represents the Objective-CC id type.
Decl * getVaListTagDecl() const
Retrieve the C type declaration corresponding to the predefined __va_list_tag type used to help defin...
QualType getUnsignedWCharType() const
Return the type of "unsigned wchar_t".
QualType getFunctionTypeWithoutParamABIs(QualType T) const
Get or construct a function type that is equivalent to the input type except that the parameter ABI a...
QualType getCorrespondingUnsaturatedType(QualType Ty) const
comments::FullComment * getCommentForDecl(const Decl *D, const Preprocessor *PP) const
Return parsed documentation comment attached to a given declaration.
TemplateArgument getInjectedTemplateArg(NamedDecl *ParamDecl) const
unsigned getTargetDefaultAlignForAttributeAligned() const
Return the default alignment for attribute((aligned)) on this target, to be used if no alignment valu...
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
llvm::DenseMap< CanQualType, SYCLKernelInfo > SYCLKernels
Map of SYCL kernels indexed by the unique type used to name the kernel.
bool isSameTemplateParameterList(const TemplateParameterList *X, const TemplateParameterList *Y) const
Determine whether two template parameter lists are similar enough that they may be used in declaratio...
QualType getWritePipeType(QualType T) const
Return a write_only pipe type for the specified type.
QualType getTypeDeclType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TypeDecl *Decl) const
bool isDestroyingOperatorDelete(const FunctionDecl *FD) const
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CanQualType UnsignedInt128Ty
CanQualType BuiltinFnTy
ObjCInterfaceDecl * getObjCProtocolDecl() const
Retrieve the Objective-C class declaration corresponding to the predefined Protocol class.
unsigned NumImplicitDefaultConstructors
The number of implicitly-declared default constructors.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
llvm::iterator_range< overridden_cxx_method_iterator > overridden_method_range
unsigned NumImplicitMoveAssignmentOperatorsDeclared
The number of implicitly-declared move assignment operators for which declarations were built.
void setManglingNumber(const NamedDecl *ND, unsigned Number)
llvm::DenseMap< const Decl *, const RawComment * > DeclRawComments
Mapping from declaration to directly attached comment.
Definition ASTContext.h:968
CanQualType OCLSamplerTy
QualType getAutoType(QualType DeducedType, AutoTypeKeyword Keyword, bool IsDependent, bool IsPack=false, TemplateDecl *TypeConstraintConcept=nullptr, ArrayRef< TemplateArgument > TypeConstraintArgs={}) const
C++11 deduced auto type.
TypedefDecl * getBuiltinVaListDecl() const
Retrieve the C type declaration corresponding to the predefined __builtin_va_list type.
CanQualType getCanonicalTypeDeclType(const TypeDecl *TD) const
CanQualType VoidTy
QualType getPackExpansionType(QualType Pattern, UnsignedOrNone NumExpansions, bool ExpectPackInType=true) const
Form a pack expansion type with the given pattern.
CanQualType UnsignedCharTy
CanQualType UnsignedShortFractTy
BuiltinTemplateDecl * buildBuiltinTemplateDecl(BuiltinTemplateKind BTK, const IdentifierInfo *II) const
void * Allocate(size_t Size, unsigned Align=8) const
Definition ASTContext.h:846
bool canBuiltinBeRedeclared(const FunctionDecl *) const
Return whether a declaration to a builtin is allowed to be overloaded/redeclared.
CanQualType UnsignedIntTy
unsigned NumImplicitMoveConstructors
The number of implicitly-declared move constructors.
QualType getTypedefType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TypedefNameDecl *Decl, QualType UnderlyingType=QualType(), std::optional< bool > TypeMatchesDeclOrNone=std::nullopt) const
Return the unique reference to the type for the specified typedef-name decl.
QualType getObjCTypeParamType(const ObjCTypeParamDecl *Decl, ArrayRef< ObjCProtocolDecl * > protocols) const
void getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT, QualType T, std::string &S, bool Extended) const
getObjCEncodingForMethodParameter - Return the encoded type for a single method parameter or return t...
void addDeclaratorForUnnamedTagDecl(TagDecl *TD, DeclaratorDecl *DD)
unsigned overridden_methods_size(const CXXMethodDecl *Method) const
std::string getObjCEncodingForBlock(const BlockExpr *blockExpr) const
Return the encoded type for this block declaration.
QualType getTemplateSpecializationType(ElaboratedTypeKeyword Keyword, TemplateName T, ArrayRef< TemplateArgument > SpecifiedArgs, ArrayRef< TemplateArgument > CanonicalArgs, QualType Underlying=QualType()) const
TypeSourceInfo * CreateTypeSourceInfo(QualType T, unsigned Size=0) const
Allocate an uninitialized TypeSourceInfo.
TemplateName getQualifiedTemplateName(NestedNameSpecifier Qualifier, bool TemplateKeyword, TemplateName Template) const
Retrieve the template name that represents a qualified template name such as std::vector.
bool isSameAssociatedConstraint(const AssociatedConstraint &ACX, const AssociatedConstraint &ACY) const
Determine whether two 'requires' expressions are similar enough that they may be used in re-declarati...
QualType getExceptionObjectType(QualType T) const
CanQualType UnknownAnyTy
void setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl, TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation=SourceLocation())
Note that the static data member Inst is an instantiation of the static data member template Tmpl of ...
FieldDecl * getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) const
DeclaratorDecl * getDeclaratorForUnnamedTagDecl(const TagDecl *TD)
bool ObjCObjectAdoptsQTypeProtocols(QualType QT, ObjCInterfaceDecl *Decl)
ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's protocol list adopt all protocols in Q...
CanQualType UnsignedLongLongTy
QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error, unsigned *IntegerConstantArgs=nullptr) const
Return the type for the specified builtin.
CanQualType OCLReserveIDTy
bool isSameTemplateParameter(const NamedDecl *X, const NamedDecl *Y) const
Determine whether two template parameters are similar enough that they may be used in declarations of...
void registerSYCLEntryPointFunction(FunctionDecl *FD)
Generates and stores SYCL kernel metadata for the provided SYCL kernel entry point function.
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
overridden_cxx_method_iterator overridden_methods_begin(const CXXMethodDecl *Method) const
CanQualType UnsignedShortTy
unsigned getTypeAlignIfKnown(QualType T, bool NeedsPreferredAlignment=false) const
Return the alignment of a type, in bits, or 0 if the type is incomplete and we cannot determine the a...
void UnwrapSimilarArrayTypes(QualType &T1, QualType &T2, bool AllowPiMismatch=true) const
Attempt to unwrap two types that may both be array types with the same bound (or both be array types ...
bool isRepresentableIntegerValue(llvm::APSInt &Value, QualType T)
Determine whether the given integral value is representable within the given type T.
bool AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
const SYCLKernelInfo & getSYCLKernelInfo(QualType T) const
Given a type used as a SYCL kernel name, returns a reference to the metadata generated from the corre...
bool canAssignObjCInterfacesInBlockPointer(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT, bool BlockReturnType)
canAssignObjCInterfacesInBlockPointer - This routine is specifically written for providing type-safet...
CanQualType SatUnsignedLongFractTy
QualType getMemberPointerType(QualType T, NestedNameSpecifier Qualifier, const CXXRecordDecl *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
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 hasDirectOwnershipQualifier(QualType Ty) const
Return true if the type has been explicitly qualified with ObjC ownership.
CanQualType FractTy
Qualifiers::ObjCLifetime getInnerObjCOwnership(QualType T) const
Recurses in pointer/array types until it finds an Objective-C retainable type and returns its ownersh...
void addCopyConstructorForExceptionObject(CXXRecordDecl *RD, CXXConstructorDecl *CD)
void deduplicateMergedDefinitionsFor(NamedDecl *ND)
Clean up the merged definition list.
DiagnosticsEngine & getDiagnostics() const
QualType getAdjustedParameterType(QualType T) const
Perform adjustment on the parameter type of a function.
CanQualType LongAccumTy
interp::Context & getInterpContext()
Returns the clang bytecode interpreter context.
CanQualType Char32Ty
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
UnnamedGlobalConstantDecl * getUnnamedGlobalConstantDecl(QualType Ty, const APValue &Value) const
Return a declaration for a uniquified anonymous global constant corresponding to a given APValue.
CanQualType SatFractTy
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size.
QualType getUnresolvedUsingType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const UnresolvedUsingTypenameDecl *D) const
bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec)
Return true if the given vector types are of the same unqualified type or if they are equivalent to t...
void getOverriddenMethods(const NamedDecl *Method, SmallVectorImpl< const NamedDecl * > &Overridden) const
Return C++ or ObjC overridden methods for the given Method.
DeclarationNameInfo getNameForTemplate(TemplateName Name, SourceLocation NameLoc) const
bool hasSameTemplateName(const TemplateName &X, const TemplateName &Y, bool IgnoreDeduced=false) const
Determine whether the given template names refer to the same template.
CanQualType SatLongFractTy
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:891
void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl)
CanQualType OCLQueueTy
CanQualType LongFractTy
CanQualType SatShortAccumTy
QualType getAutoDeductType() const
C++11 deduction pattern for 'auto' type.
CanQualType BFloat16Ty
unsigned NumImplicitCopyConstructors
The number of implicitly-declared copy constructors.
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
CanQualType IncompleteMatrixIdxTy
void getFunctionFeatureMap(llvm::StringMap< bool > &FeatureMap, const FunctionDecl *) const
CanQualType getNSIntegerType() const
QualType getCorrespondingUnsignedType(QualType T) const
void setBlockVarCopyInit(const VarDecl *VD, Expr *CopyExpr, bool CanThrow)
Set the copy initialization expression of a block var decl.
TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin, UnresolvedSetIterator End) const
Retrieve the template name that corresponds to a non-empty lookup.
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
TemplateName getSubstTemplateTemplateParmPack(const TemplateArgument &ArgPack, Decl *AssociatedDecl, unsigned Index, bool Final) const
QualType getDeducedTemplateSpecializationType(ElaboratedTypeKeyword Keyword, TemplateName Template, QualType DeducedType, bool IsDependent) const
C++17 deduced class template specialization type.
TargetCXXABI::Kind getCXXABIKind() const
Return the C++ ABI kind that should be used.
QualType getHLSLAttributedResourceType(QualType Wrapped, QualType Contained, const HLSLAttributedResourceType::Attributes &Attrs)
bool UnwrapSimilarTypes(QualType &T1, QualType &T2, bool AllowPiMismatch=true) const
Attempt to unwrap two types that may be similar (C++ [conv.qual]).
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
QualType getSignedSizeType() const
Return the unique signed counterpart of the integer type corresponding to size_t.
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any.
uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const
Return number of constant array elements.
CanQualType SatUnsignedLongAccumTy
QualType getUnconstrainedType(QualType T) const
Remove any type constraints from a template parameter type, for equivalence comparison of template pa...
CanQualType LongLongTy
CanQualType getCanonicalTagType(const TagDecl *TD) const
bool isSameTemplateArgument(const TemplateArgument &Arg1, const TemplateArgument &Arg2) const
Determine whether the given template arguments Arg1 and Arg2 are equivalent.
QualType getTypeOfType(QualType QT, TypeOfKind Kind) const
getTypeOfType - Unlike many "get<Type>" functions, we don't unique TypeOfType nodes.
QualType getCorrespondingSignedType(QualType T) const
QualType mergeObjCGCQualifiers(QualType, QualType)
mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and 'RHS' attributes and ret...
llvm::DenseMap< const Decl *, const Decl * > CommentlessRedeclChains
Keeps track of redeclaration chains that don't have any comment attached.
Definition ASTContext.h:984
uint64_t getArrayInitLoopExprElementCount(const ArrayInitLoopExpr *AILE) const
Return number of elements initialized in an ArrayInitLoopExpr.
unsigned getTargetAddressSpace(LangAS AS) const
QualType getIntPtrType() const
Return a type compatible with "intptr_t" (C99 7.18.1.4), as defined by the target.
void mergeDefinitionIntoModule(NamedDecl *ND, Module *M, bool NotifyListeners=true)
Note that the definition ND has been merged into module M, and should be visible whenever M is visibl...
QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return a non-unique reference to the type for a dependently-sized array of the specified element type...
void addTranslationUnitDecl()
CanQualType WCharTy
void getObjCEncodingForPropertyType(QualType T, std::string &S) const
Emit the Objective-C property type encoding for the given type T into S.
unsigned NumImplicitCopyAssignmentOperators
The number of implicitly-declared copy assignment operators.
void CollectInheritedProtocols(const Decl *CDecl, llvm::SmallPtrSet< ObjCProtocolDecl *, 8 > &Protocols)
CollectInheritedProtocols - Collect all protocols in current class and those inherited by it.
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
llvm::DenseMap< const Decl *, const Decl * > RedeclChainComments
Mapping from canonical declaration to the first redeclaration in chain that has a comment attached.
Definition ASTContext.h:975
void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType)
Change the result type of a function type once it is deduced.
QualType getObjCGCQualType(QualType T, Qualifiers::GC gcAttr) const
Return the uniqued reference to the type for an Objective-C gc-qualified type.
QualType getDecltypeType(Expr *e, QualType UnderlyingType) const
C++11 decltype.
std::optional< CXXRecordDeclRelocationInfo > getRelocationInfoForCXXRecord(const CXXRecordDecl *) const
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...
unsigned char getFixedPointScale(QualType Ty) const
QualType getIncompleteArrayType(QualType EltTy, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return a unique reference to the type for an incomplete array of the specified element type.
QualType getDependentSizedExtVectorType(QualType VectorType, Expr *SizeExpr, SourceLocation AttrLoc) const
QualType DecodeTypeStr(const char *&Str, const ASTContext &Context, ASTContext::GetBuiltinTypeError &Error, bool &RequireICE, bool AllowTypeModifiers) const
TemplateName getAssumedTemplateName(DeclarationName Name) const
Retrieve a template name representing an unqualified-id that has been assumed to name a template for ...
@ GE_None
No error.
@ GE_Missing_type
Missing a type.
QualType adjustStringLiteralBaseType(QualType StrLTy) const
uint16_t getPointerAuthTypeDiscriminator(QualType T)
Return the "other" type-specific discriminator for the given type.
bool canonicalizeTemplateArguments(MutableArrayRef< TemplateArgument > Args) const
Canonicalize the given template argument list.
QualType getTypeOfExprType(Expr *E, TypeOfKind Kind) const
C23 feature and GCC extension.
CanQualType Char8Ty
QualType getSignedWCharType() const
Return the type of "signed wchar_t".
QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals) const
Return this type as a completely-unqualified array type, capturing the qualifiers in Quals.
bool hasCvrSimilarType(QualType T1, QualType T2)
Determine if two types are similar, ignoring only CVR qualifiers.
TemplateName getDeducedTemplateName(TemplateName Underlying, DefaultArguments DefaultArgs) const
Represents a TemplateName which had some of its default arguments deduced.
ObjCImplementationDecl * getObjCImplementation(ObjCInterfaceDecl *D)
Get the implementation of the ObjCInterfaceDecl D, or nullptr if none exists.
CanQualType HalfTy
CanQualType UnsignedAccumTy
void setObjCMethodRedeclaration(const ObjCMethodDecl *MD, const ObjCMethodDecl *Redecl)
void addTypedefNameForUnnamedTagDecl(TagDecl *TD, TypedefNameDecl *TND)
QualType getConstantMatrixType(QualType ElementType, unsigned NumRows, unsigned NumColumns) const
Return the unique reference to the matrix type of the specified element type and size.
const CXXRecordDecl * baseForVTableAuthentication(const CXXRecordDecl *ThisClass) const
Resolve the root record to be used to derive the vtable pointer authentication policy for the specifi...
QualType getVariableArrayDecayedType(QualType Ty) const
Returns a vla type where known sizes are replaced with [*].
void setCFConstantStringType(QualType T)
const SYCLKernelInfo * findSYCLKernelInfo(QualType T) const
Returns a pointer to the metadata generated from the corresponding SYCLkernel entry point if the prov...
unsigned getParameterIndex(const ParmVarDecl *D) const
Used by ParmVarDecl to retrieve on the side the index of the parameter when it exceeds the size of th...
QualType getCommonSugaredType(QualType X, QualType Y, bool Unqualified=false) const
CanQualType OCLEventTy
void AddDeallocation(void(*Callback)(void *), void *Data) const
Add a deallocation callback that will be invoked when the ASTContext is destroyed.
AttrVec & getDeclAttrs(const Decl *D)
Retrieve the attributes for the given declaration.
CXXMethodVector::const_iterator overridden_cxx_method_iterator
RawComment * getRawCommentForDeclNoCacheImpl(const Decl *D, const SourceLocation RepresentativeLocForDecl, const std::map< unsigned, RawComment * > &CommentsInFile) const
unsigned getTypeAlign(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in bits.
QualType mergeTransparentUnionType(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false)
mergeTransparentUnionType - if T is a transparent union type and a member of T is compatible with Sub...
QualType isPromotableBitField(Expr *E) const
Whether this is a promotable bitfield reference according to C99 6.3.1.1p2, bullet 2 (and GCC extensi...
bool isSentinelNullExpr(const Expr *E)
CanQualType getNSUIntegerType() const
void setIsDestroyingOperatorDelete(const FunctionDecl *FD, bool IsDestroying)
uint64_t getCharWidth() const
Return the size of the character type, in bits.
QualType getBitIntType(bool Unsigned, unsigned NumBits) const
Return a bit-precise integer type with the specified signedness and bit count.
unsigned NumImplicitMoveAssignmentOperators
The number of implicitly-declared move assignment operators.
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
virtual void DeducedReturnType(const FunctionDecl *FD, QualType ReturnType)
A function's return type has been deduced.
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
CharUnits getAlignment() const
getAlignment - Get the record alignment in characters.
const CXXRecordDecl * getBaseSharingVBPtr() const
CharUnits getSize() const
getSize - Get the record size in characters.
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
CharUnits getDataSize() const
getDataSize() - Get the record data size, which is the record size without tail padding,...
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
CharUnits getVBaseClassOffset(const CXXRecordDecl *VBase) const
getVBaseClassOffset - Get the offset, in chars, for the given base class.
CharUnits getNonVirtualSize() const
getNonVirtualSize - Get the non-virtual size (in chars) of an object, which is the size of the object...
CharUnits getUnadjustedAlignment() const
getUnadjustedAlignment - Get the record alignment in characters, before alignment adjustment.
Represents a type which was implicitly adjusted by the semantic engine for arbitrary reasons.
Definition TypeBase.h:3489
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3510
Represents a loop initializing the elements of an array.
Definition Expr.h:5902
llvm::APInt getArraySize() const
Definition Expr.h:5924
Expr * getSubExpr() const
Get the initializer to use for each array element.
Definition Expr.h:5922
Represents a constant array type that does not decay to a pointer when used as a function parameter.
Definition TypeBase.h:3892
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3722
ArraySizeModifier getSizeModifier() const
Definition TypeBase.h:3736
Qualifiers getIndexTypeQualifiers() const
Definition TypeBase.h:3740
QualType getElementType() const
Definition TypeBase.h:3734
unsigned getIndexTypeCVRQualifiers() const
Definition TypeBase.h:3744
A structure for storing the information associated with a name that has been assumed to be a template...
AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, __atomic_load,...
Definition Expr.h:6814
Expr * getPtr() const
Definition Expr.h:6845
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:8082
Attr - This represents one attribute.
Definition Attr.h:44
A fixed int type of a specified bitwidth.
Definition TypeBase.h:8130
void Profile(llvm::FoldingSetNodeID &ID) const
Definition TypeBase.h:8147
unsigned getNumBits() const
Definition TypeBase.h:8142
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition Decl.h:4654
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition Expr.h:6558
Pointer to a block type.
Definition TypeBase.h:3542
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3559
Represents the builtin template declaration which is used to implement __make_integer_seq and other b...
static BuiltinTemplateDecl * Create(const ASTContext &C, DeclContext *DC, DeclarationName Name, BuiltinTemplateKind BTK)
This class is used for builtin types like 'int'.
Definition TypeBase.h:3164
Kind getKind() const
Definition TypeBase.h:3212
StringRef getName(const PrintingPolicy &Policy) const
Definition Type.cpp:3362
Holds information about both target-independent and target-specific builtins, allowing easy queries b...
Definition Builtins.h:228
Implements C++ ABI-specific semantic analysis functions.
Definition CXXABI.h:29
virtual ~CXXABI()
Represents a C++ constructor within a class.
Definition DeclCXX.h:2604
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2129
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2225
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr)
Definition DeclCXX.cpp:132
CXXRecordDecl * getDefinition() const
Definition DeclCXX.h:548
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition DeclCXX.h:1214
bool isDynamicClass() const
Definition DeclCXX.h:574
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition DeclCXX.h:1186
SplitQualType split() const
static CanQual< Type > CreateUnsafe(QualType Other)
QualType withConst() const
Retrieves a version of this type with const applied.
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
Qualifiers getQualifiers() const
Retrieve all qualifiers.
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
bool isPositive() const
isPositive - Test whether the quantity is greater than zero.
Definition CharUnits.h:128
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition CharUnits.h:122
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:63
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition CharUnits.h:53
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3275
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3290
bool hasExplicitTemplateArgs() const
Whether or not template arguments were explicitly specified in the concept reference (they might not ...
Definition ASTConcept.h:209
const ASTTemplateArgumentListInfo * getTemplateArgsAsWritten() const
Definition ASTConcept.h:203
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3760
const Expr * getSizeExpr() const
Return a pointer to the size expression.
Definition TypeBase.h:3856
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3816
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition TypeBase.h:3875
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3836
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4373
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition TypeBase.h:4392
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:4399
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition TypeBase.h:4389
Represents a sugar type with __counted_by or __sized_by annotations, including their _or_null variant...
Definition TypeBase.h:3436
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3472
Represents a pointer type decayed from an array or function type.
Definition TypeBase.h:3525
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1449
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2109
bool isFileContext() const
Definition DeclBase.h:2180
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition DeclBase.h:2125
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
void addDecl(Decl *D)
Add the declaration D into this context.
Decl::Kind getDeclKind() const
Definition DeclBase.h:2102
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1270
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
const DeclContext * getParentFunctionOrMethod(bool LexicalParent=false) const
If this decl is defined inside a function/method/block it returns the corresponding DeclContext,...
Definition DeclBase.cpp:341
bool isModuleLocal() const
Whether this declaration was a local declaration to a C++20 named module.
T * getAttr() const
Definition DeclBase.h:573
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:546
void addAttr(Attr *A)
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:593
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl,...
Definition DeclBase.cpp:560
bool isUnconditionallyVisible() const
Determine whether this declaration is definitely visible to name lookup, independent of whether the o...
Definition DeclBase.h:859
static Decl * castFromDeclContext(const DeclContext *)
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition DeclBase.cpp:308
bool isCanonicalDecl() const
Whether this particular Decl is a canonical one.
Definition DeclBase.h:984
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition DeclBase.h:842
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition DeclBase.cpp: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:588
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:559
SourceLocation getLocation() const
Definition DeclBase.h:439
void setImplicit(bool I=true)
Definition DeclBase.h:594
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition DeclBase.h:1049
DeclContext * getDeclContext()
Definition DeclBase.h:448
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:431
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition DeclBase.cpp:382
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:918
bool hasAttr() const
Definition DeclBase.h:577
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:978
Kind getKind() const
Definition DeclBase.h:442
DeclarationNameLoc - Additional source/type location info for a declaration name.
static DeclarationNameLoc makeCXXOperatorNameLoc(SourceLocation BeginLoc, SourceLocation EndLoc)
Construct location information for a non-literal C++ operator.
The name of a declaration.
static int compare(DeclarationName LHS, DeclarationName RHS)
Represents a ValueDecl that came out of a declarator.
Definition Decl.h: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:4061
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4083
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:8175
Represents an array type in C++ whose size is a value-dependent expression.
Definition TypeBase.h:4011
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4040
Represents an extended vector type where either the type or size is dependent.
Definition TypeBase.h:4101
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4126
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition TypeBase.h:4420
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4440
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:6199
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:6204
Represents a vector type where either the type or size is dependent.
Definition TypeBase.h:4227
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4252
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:232
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
Definition Diagnostic.h:905
Represents an enum.
Definition Decl.h:4007
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition Decl.h:4216
bool isComplete() const
Returns true if this can be considered a complete type.
Definition Decl.h:4230
EnumDecl * getDefinitionOrSelf() const
Definition Decl.h:4114
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4171
This represents one expression.
Definition Expr.h:112
bool isIntegerConstantExpr(const ASTContext &Ctx) const
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3090
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:444
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:194
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition Expr.cpp:4203
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:831
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on.
Definition Expr.h:223
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3065
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant.
Definition Expr.cpp:4042
QualType getType() const
Definition Expr.h:144
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition Expr.h:434
We can encode up to four bits in the low bits of a type pointer, but there are many more type qualifi...
Definition TypeBase.h:1717
void Profile(llvm::FoldingSetNodeID &ID) const
Definition TypeBase.h:1764
ExtVectorType - Extended vector type.
Definition TypeBase.h:4267
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:5468
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:3160
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3263
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition Decl.cpp:4741
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition Decl.h:3245
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3396
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:4689
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:2000
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition Decl.h:2689
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3751
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition Decl.h:2921
bool isMSExternInline() const
The combination of the extern and inline keywords under MSVC forces the function to be required.
Definition Decl.cpp:3880
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3736
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:4406
bool isUserProvided() const
True if this method is user-declared and was not deleted or defaulted on its first declaration.
Definition Decl.h:2410
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:4067
FunctionDecl * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
SmallVector< Conflict > Conflicts
Definition TypeBase.h:5222
static FunctionEffectSet getIntersection(FunctionEffectsRef LHS, FunctionEffectsRef RHS)
Definition Type.cpp:5633
static FunctionEffectSet getUnion(FunctionEffectsRef LHS, FunctionEffectsRef RHS, Conflicts &Errs)
Definition Type.cpp:5671
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5054
ArrayRef< EffectConditionExpr > conditions() const
Definition TypeBase.h:5088
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition TypeBase.h:4832
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:4848
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5254
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition TypeBase.h:5758
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition TypeBase.h:5561
unsigned getNumParams() const
Definition TypeBase.h:5532
QualType getParamType(unsigned i) const
Definition TypeBase.h:5534
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition Type.cpp:3955
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition TypeBase.h:5567
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5658
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5543
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5539
ArrayRef< ExtParameterInfo > getExtParameterInfos() const
Definition TypeBase.h:5727
bool hasExtParameterInfos() const
Is there any interesting extra information for any of the parameters of this function type?
Definition TypeBase.h:5723
Declaration of a template function.
A class which abstracts out some details necessary for making a call.
Definition TypeBase.h:4561
CallingConv getCC() const
Definition TypeBase.h:4620
unsigned getRegParm() const
Definition TypeBase.h:4613
bool getNoCallerSavedRegs() const
Definition TypeBase.h:4609
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4632
Interesting information about a specific parameter that can't simply be reflected in parameter's type...
Definition TypeBase.h:4476
ExtParameterInfo withIsNoEscape(bool NoEscape) const
Definition TypeBase.h:4516
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4450
ExtInfo getExtInfo() const
Definition TypeBase.h:4806
QualType getReturnType() const
Definition TypeBase.h:4790
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:5035
Represents a C array with an unspecified size.
Definition TypeBase.h:3909
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3926
static ItaniumMangleContext * create(ASTContext &Context, DiagnosticsEngine &Diags, bool IsAux=false)
@ Relative
Components in the vtable are relative offsets between the vtable and the other structs/functions.
@ Pointer
Components in the vtable are pointers to other structs/functions.
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3617
@ Swift
Interoperability with the latest known version of the Swift runtime.
@ Swift4_2
Interoperability with the Swift 4.2 runtime.
@ Swift4_1
Interoperability with the Swift 4.1 runtime.
@ Integer
Permit vector bitcasts between integer vectors with different numbers of elements but the same total ...
@ All
Permit vector bitcasts between all vectors with the same total bit-width.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
std::optional< TargetCXXABI::Kind > CXXABI
C++ ABI to compile with, if specified by the frontend through -fc++-abi=.
clang::ObjCRuntime ObjCRuntime
CoreFoundationABI CFRuntime
A global _GUID constant.
Definition DeclCXX.h:4398
static void Profile(llvm::FoldingSetNodeID &ID, Parts P)
Definition DeclCXX.h:4435
MSGuidDeclParts Parts
Definition DeclCXX.h:4400
Sugar type that represents a type that was qualified by a qualifier written as a macro invocation.
Definition TypeBase.h:6133
MangleContext - Context for tracking state which persists across multiple calls to the C++ name mangl...
Definition Mangle.h:52
Keeps track of the mangled names of lambda expressions and block literals within a particular context...
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition TypeBase.h:4351
static bool isValidElementType(QualType T)
Valid elements types are the following:
Definition TypeBase.h:4358
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3653
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3696
Provides information a specialization of a member of a class template, which may be a member function...
static MicrosoftMangleContext * create(ASTContext &Context, DiagnosticsEngine &Diags, bool IsAux=false)
Describes a module or submodule.
Definition Module.h:144
bool isNamedModule() const
Does this Module is a named module of a standard named module?
Definition Module.h:224
This represents a decl that may have a name.
Definition Decl.h: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:3261
A C++ nested-name-specifier augmented with source location information.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
NestedNameSpecifier getCanonical() const
Retrieves the "canonical" nested name specifier for a given nested name specifier.
CXXRecordDecl * getAsMicrosoftSuper() const
NamespaceAndPrefix getAsNamespaceAndPrefix() const
bool isCanonical() const
Whether this nested name specifier is canonical.
Kind
The kind of specifier that completes this nested name specifier.
@ MicrosoftSuper
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
@ Global
The global specifier '::'. There is no stored value.
@ Namespace
A namespace-like entity, stored as a NamespaceBaseDecl*.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
static NonTypeTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, unsigned D, unsigned P, const IdentifierInfo *Id, QualType T, bool ParameterPack, TypeSourceInfo *TInfo)
Helper data structure representing the traits in a match clause of an declare variant or metadirectiv...
ObjCCategoryDecl - Represents a category declaration.
Definition DeclObjC.h:2329
ObjCCategoryImplDecl - An object of this class encapsulates a category @implementation declaration.
Definition DeclObjC.h:2545
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition DeclObjC.h:2597
Represents an ObjC class declaration.
Definition DeclObjC.h:1154
ObjCTypeParamList * getTypeParamList() const
Retrieve the type parameters of this class.
Definition DeclObjC.cpp:319
static ObjCInterfaceDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation atLoc, const IdentifierInfo *Id, ObjCTypeParamList *typeParamList, ObjCInterfaceDecl *PrevDecl, SourceLocation ClassLoc=SourceLocation(), bool isInternal=false)
bool hasDefinition() const
Determine whether this class has been defined.
Definition DeclObjC.h:1528
ivar_range ivars() const
Definition DeclObjC.h:1451
bool ClassImplementsProtocol(ObjCProtocolDecl *lProto, bool lookupCategory, bool RHSIsQualifiedID=false)
ClassImplementsProtocol - Checks that 'lProto' protocol has been implemented in IDecl class,...
StringRef getObjCRuntimeNameAsString() const
Produce a name to be used for class's metadata.
ObjCImplementationDecl * getImplementation() const
ObjCInterfaceDecl * getSuperClass() const
Definition DeclObjC.cpp:349
bool isSuperClassOf(const ObjCInterfaceDecl *I) const
isSuperClassOf - Return true if this class is the specified class or is a super class of the specifie...
Definition DeclObjC.h:1810
known_extensions_range known_extensions() const
Definition DeclObjC.h:1762
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition TypeBase.h:7840
ObjCInterfaceDecl * getDecl() const
Get the declaration of this interface.
Definition Type.cpp:951
ObjCIvarDecl - Represents an ObjC instance variable.
Definition DeclObjC.h:1952
ObjCIvarDecl * getNextIvar()
Definition DeclObjC.h:1987
ObjCMethodDecl - Represents an instance or class method declaration.
Definition DeclObjC.h:140
ObjCDeclQualifier getObjCDeclQualifier() const
Definition DeclObjC.h:246
unsigned param_size() const
Definition DeclObjC.h:347
param_const_iterator param_end() const
Definition DeclObjC.h:358
param_const_iterator param_begin() const
Definition DeclObjC.h:354
bool isVariadic() const
Definition DeclObjC.h:431
const ParmVarDecl *const * param_const_iterator
Definition DeclObjC.h:349
Selector getSelector() const
Definition DeclObjC.h:327
bool isInstanceMethod() const
Definition DeclObjC.h:426
QualType getReturnType() const
Definition DeclObjC.h:329
Represents a pointer to an Objective C object.
Definition TypeBase.h:7896
bool isObjCQualifiedClassType() const
True if this is equivalent to 'Class.
Definition TypeBase.h:7977
const ObjCObjectPointerType * stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const
Strip off the Objective-C "kindof" type and (with it) any protocol qualifiers.
Definition Type.cpp:958
bool isObjCQualifiedIdType() const
True if this is equivalent to 'id.
Definition TypeBase.h:7971
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:8053
const ObjCObjectType * getObjectType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:7933
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition TypeBase.h:7954
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:7908
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition TypeBase.h:7948
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition Type.cpp:1840
qual_range quals() const
Definition TypeBase.h:8015
bool isObjCClassType() const
True if this is equivalent to the 'Class' type, i.e.
Definition TypeBase.h:7960
Represents one property declaration in an Objective-C interface.
Definition DeclObjC.h:731
bool isReadOnly() const
isReadOnly - Return true iff the property has a setter.
Definition DeclObjC.h:838
static ObjCPropertyDecl * findPropertyDecl(const DeclContext *DC, const IdentifierInfo *propertyID, ObjCPropertyQueryKind queryKind)
Lookup a property by name in the specified DeclContext.
Definition DeclObjC.cpp:176
bool isOptional() const
Definition DeclObjC.h:916
SetterKind getSetterKind() const
getSetterKind - Return the method used for doing assignment in the property setter.
Definition DeclObjC.h:873
Selector getSetterName() const
Definition DeclObjC.h:893
QualType getType() const
Definition DeclObjC.h:804
Selector getGetterName() const
Definition DeclObjC.h:885
ObjCPropertyAttribute::Kind getPropertyAttributes() const
Definition DeclObjC.h:815
ObjCPropertyImplDecl - Represents implementation declaration of a property in a class or category imp...
Definition DeclObjC.h:2805
ObjCIvarDecl * getPropertyIvarDecl() const
Definition DeclObjC.h:2879
Represents an Objective-C protocol declaration.
Definition DeclObjC.h:2084
protocol_range protocols() const
Definition DeclObjC.h:2161
bool isGNUFamily() const
Is this runtime basically of the GNU family of runtimes?
Represents the declaration of an Objective-C type parameter.
Definition DeclObjC.h:578
ObjCTypeParamVariance getVariance() const
Determine the variance of this type parameter.
Definition DeclObjC.h:623
Stores a list of Objective-C type parameters for a parameterized class or a category/extension thereo...
Definition DeclObjC.h:662
A structure for storing the information associated with an overloaded template name.
Represents a C++11 pack expansion that produces a sequence of expressions.
Definition ExprCXX.h:4365
Sugar for parentheses used when specifying types.
Definition TypeBase.h:3302
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3316
void clear()
Clear parent maps.
Represents a parameter to a function.
Definition Decl.h:1790
ObjCDeclQualifier getObjCDeclQualifier() const
Definition Decl.h:1854
QualType getOriginalType() const
Definition Decl.cpp:2955
ParsedAttr - Represents a syntactic attribute.
Definition ParsedAttr.h:119
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:8113
Pointer-authentication qualifiers.
Definition TypeBase.h:152
static PointerAuthQualifier Create(unsigned Key, bool IsAddressDiscriminated, unsigned ExtraDiscriminator, PointerAuthenticationMode AuthenticationMode, bool IsIsaPointer, bool AuthenticatesNullValues)
Definition TypeBase.h:239
bool isEquivalent(PointerAuthQualifier Other) const
Definition TypeBase.h:301
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3328
QualType getPointeeType() const
Definition TypeBase.h:3338
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3343
PredefinedSugarKind Kind
Definition TypeBase.h:8189
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
A (possibly-)qualified type.
Definition TypeBase.h:937
bool hasAddressDiscriminatedPointerAuth() const
Definition TypeBase.h:1457
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8362
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition Type.cpp:2866
Qualifiers::GC getObjCGCAttr() const
Returns gc attribute of this type.
Definition TypeBase.h:8409
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8367
QualType getDesugaredType(const ASTContext &Context) const
Return the specified type with any "sugar" removed from the type.
Definition TypeBase.h:1296
QualType withConst() const
Definition TypeBase.h:1159
bool hasLocalQualifiers() const
Determine whether this particular QualType instance has any qualifiers, without looking through any t...
Definition TypeBase.h:1064
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8278
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8404
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8318
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1438
QualType getCanonicalType() const
Definition TypeBase.h:8330
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8372
SplitQualType split() const
Divides a QualType into its unqualified type and a set of local qualifiers.
Definition TypeBase.h:8299
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8351
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition TypeBase.h:1545
bool isCanonical() const
Definition TypeBase.h:8335
const Type * getTypePtrOrNull() const
Definition TypeBase.h:8282
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1332
PrimitiveCopyKind isNonTrivialToPrimitiveDestructiveMove() const
Check if this is a non-trivial type that would cause a C struct transitively containing this type to ...
Definition Type.cpp:2989
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition TypeBase.h:8310
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:8218
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition TypeBase.h:8225
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:3635
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:4312
bool isLambda() const
Determine whether this record is a class describing a lambda function object.
Definition Decl.cpp:5173
bool hasFlexibleArrayMember() const
Definition Decl.h:4345
field_range fields() const
Definition Decl.h:4515
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition Decl.cpp:5159
RecordDecl * getMostRecentDecl()
Definition Decl.h:4338
virtual void completeDefinition()
Note that the definition of this type is now complete.
Definition Decl.cpp:5218
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition Decl.h:4496
bool field_empty() const
Definition Decl.h:4523
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:3573
QualType getPointeeType() const
Definition TypeBase.h:3591
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3599
This table allows us to fully hide how we implement multi-keyword caching.
std::string getAsString() const
Derive the full selector name (e.g.
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
This class handles loading and caching of source files into memory.
A trivial tuple used to represent a source range.
SourceLocation getBegin() const
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, bool Canonical, bool ProfileLambdaExpr=false) const
Produce a unique representation of the given statement.
The streaming interface shared between DiagnosticBuilder and PartialDiagnostic.
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1799
static StringLiteral * Create(const ASTContext &Ctx, StringRef Str, StringLiteralKind Kind, bool Pascal, QualType Ty, ArrayRef< SourceLocation > Locs)
This is the "fully general" constructor that allows representation of strings formed from one or more...
Definition Expr.cpp:1184
A structure for storing an already-substituted template template parameter pack.
Decl * getAssociatedDecl() const
A template-like entity which owns the whole pattern being substituted.
void Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context)
TemplateTemplateParmDecl * getParameterPack() const
Retrieve the template template parameter pack being substituted.
TemplateArgument getArgumentPack() const
Retrieve the template template argument pack with which this parameter was substituted.
unsigned getIndex() const
Returns the index of the replaced parameter in the associated declaration.
A structure for storing the information associated with a substituted template template parameter.
void Profile(llvm::FoldingSetNodeID &ID)
TemplateTemplateParmDecl * getParameter() const
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3717
TagTypeKind TagKind
Definition Decl.h:3722
TypedefNameDecl * getTypedefNameForAnonDecl() const
Definition Decl.h:3948
void startDefinition()
Starts the definition of this tag declaration.
Definition Decl.cpp:4895
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:4888
bool isUnion() const
Definition Decl.h:3922
TagKind getTagKind() const
Definition Decl.h:3911
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Kind
The basic C++ ABI kind.
static Kind getKind(StringRef Name)
Exposes information about the current target.
Definition TargetInfo.h:226
TargetOptions & getTargetOpts() const
Retrieve the target options.
Definition TargetInfo.h:323
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
unsigned getMaxAtomicInlineWidth() const
Return the maximum width lock-free atomic operation which can be inlined given the supported features...
Definition TargetInfo.h:853
virtual LangAS getCUDABuiltinAddressSpace(unsigned AS) const
Map from the address space field in builtin description strings to the language address space.
virtual LangAS getOpenCLBuiltinAddressSpace(unsigned AS) const
Map from the address space field in builtin description strings to the language address space.
unsigned getDefaultAlignForAttributeAligned() const
Return the default alignment for attribute((aligned)) on this target, to be used if no alignment valu...
Definition TargetInfo.h:746
BuiltinVaListKind
The different kinds of __builtin_va_list types defined by the target implementation.
Definition TargetInfo.h:330
@ AArch64ABIBuiltinVaList
__builtin_va_list as defined by the AArch64 ABI http://infocenter.arm.com/help/topic/com....
Definition TargetInfo.h:339
@ PowerABIBuiltinVaList
__builtin_va_list as defined by the Power ABI: https://www.power.org /resources/downloads/Power-Arch-...
Definition TargetInfo.h:344
@ AAPCSABIBuiltinVaList
__builtin_va_list as defined by ARM AAPCS ABI http://infocenter.arm.com
Definition TargetInfo.h:353
@ CharPtrBuiltinVaList
typedef char* __builtin_va_list;
Definition TargetInfo.h:332
@ VoidPtrBuiltinVaList
typedef void* __builtin_va_list;
Definition TargetInfo.h:335
@ X86_64ABIBuiltinVaList
__builtin_va_list as defined by the x86-64 ABI: http://refspecs.linuxbase.org/elf/x86_64-abi-0....
Definition TargetInfo.h:348
virtual uint64_t getNullPointerValue(LangAS AddrSpace) const
Get integer value for null pointer.
Definition TargetInfo.h:502
static bool isTypeSigned(IntType T)
Returns true if the type is signed; false otherwise.
IntType getPtrDiffType(LangAS AddrSpace) const
Definition TargetInfo.h:404
IntType getSizeType() const
Definition TargetInfo.h:385
FloatModeKind getRealTypeByWidth(unsigned BitWidth, FloatModeKind ExplicitType) const
Return floating point type with specified width.
virtual IntType getIntTypeByWidth(unsigned BitWidth, bool IsSigned) const
Return integer type with specified width.
unsigned getMaxAlignedAttribute() const
Get the maximum alignment in bits for a static variable with aligned attribute.
Definition TargetInfo.h:970
virtual unsigned getMinGlobalAlign(uint64_t Size, bool HasNonWeakDef) const
getMinGlobalAlign - Return the minimum alignment of a global variable, unless its alignment is explic...
Definition TargetInfo.h:754
unsigned getTargetAddressSpace(LangAS AS) const
IntType getSignedSizeType() const
Definition TargetInfo.h:386
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
bool useAddressSpaceMapMangling() const
Specify if mangling based on address space map should be used or not for language specific address sp...
llvm::StringMap< bool > FeatureMap
The map of which features have been enabled disabled based on the command line.
A convenient class for passing around template argument information.
ArrayRef< TemplateArgumentLoc > arguments() const
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
Location wrapper for a TemplateArgument.
Represents a template argument.
ArrayRef< TemplateArgument > getPackAsArray() const
Return the array of arguments in this template argument pack.
QualType getStructuralValueType() const
Get the type of a StructuralValue.
QualType getParamTypeForDecl() const
Expr * getAsExpr() const
Retrieve the template argument as an expression.
UnsignedOrNone getNumTemplateExpansions() const
Retrieve the number of expansions that a template template argument expansion will produce,...
QualType getAsType() const
Retrieve the type for a type template argument.
llvm::APSInt getAsIntegral() const
Retrieve the template argument as an integral value.
QualType getNullPtrType() const
Retrieve the type for null non-type template argument.
static TemplateArgument CreatePackCopy(ASTContext &Context, ArrayRef< TemplateArgument > Args)
Create a new template argument pack by copying the given set of template arguments.
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
bool structurallyEquals(const TemplateArgument &Other) const
Determines whether two template arguments are superficially the same.
QualType getIntegralType() const
Retrieve the type of the integral value.
bool getIsDefaulted() const
If returns 'true', this TemplateArgument corresponds to a default template parameter.
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
ArrayRef< TemplateArgument > pack_elements() const
Iterator range referencing all of the elements of a template argument pack.
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
@ Template
The template argument is a template name that was provided for a template template parameter.
@ StructuralValue
The template argument is a non-type template argument that can't be represented by the special-case D...
@ Pack
The template argument is actually a parameter pack.
@ TemplateExpansion
The template argument is a pack expansion of a template name that was provided for a template templat...
@ NullPtr
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
@ Type
The template argument is a type.
@ Null
Represents an empty template argument, e.g., one that has not been deduced.
@ Integral
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
ArgKind getKind() const
Return the kind of stored template argument.
TemplateName getAsTemplateOrTemplatePattern() const
Retrieve the template argument as a template name; if the argument is a pack expansion,...
const APValue & getAsStructuralValue() const
Get the value of a StructuralValue.
The base class of all kinds of template declarations (e.g., class, function, etc.).
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Represents a C++ template name within the type system.
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
DeducedTemplateStorage * getAsDeducedTemplateName() const
Retrieve the deduced template info, if any.
DependentTemplateName * getAsDependentTemplateName() const
Retrieve the underlying dependent template name structure, if any.
std::optional< TemplateName > desugar(bool IgnoreDeduced) const
OverloadedTemplateStorage * getAsOverloadedTemplate() const
Retrieve the underlying, overloaded function template declarations that this template name refers to,...
AssumedTemplateStorage * getAsAssumedTemplateName() const
Retrieve information on a name that has been assumed to be a template-name in order to permit a call ...
NameKind getKind() const
void * getAsVoidPointer() const
Retrieve the template name as a void pointer.
@ UsingTemplate
A template name that refers to a template declaration found through a specific using shadow declarati...
@ OverloadedTemplate
A set of overloaded template declarations.
@ Template
A single template declaration.
@ DependentTemplate
A dependent template name that has not been resolved to a template (or set of templates).
@ SubstTemplateTemplateParm
A template template parameter that has been substituted for some other template name.
@ SubstTemplateTemplateParmPack
A template template parameter pack that has been substituted for a template template argument pack,...
@ DeducedTemplate
A template name that refers to another TemplateName with deduced default arguments.
@ QualifiedTemplate
A qualified template name, where the qualification is kept to describe the source code as written.
@ AssumedTemplate
An unqualified-id that has been assumed to name a function template that will be found by ADL.
UsingShadowDecl * getAsUsingShadowDecl() const
Retrieve the using shadow declaration through which the underlying template declaration is introduced...
SubstTemplateTemplateParmPackStorage * getAsSubstTemplateTemplateParmPack() const
Retrieve the substituted template template parameter pack, if known.
SubstTemplateTemplateParmStorage * getAsSubstTemplateTemplateParm() const
Retrieve the substituted template template parameter, if known.
A template parameter object.
static void Profile(llvm::FoldingSetNodeID &ID, QualType T, const APValue &V)
Stores a list of template parameters for a TemplateDecl and its derived classes.
NamedDecl * getParam(unsigned Idx)
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
NamedDecl *const * const_iterator
Iterates through the template parameters in this list.
Expr * getRequiresClause()
The constraint-expression of the associated requires-clause.
ArrayRef< NamedDecl * > asArray()
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
TemplateNameKind templateParameterKind() const
unsigned getPosition() const
Get the position of the template parameter within its parameter list.
static TemplateTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation L, unsigned D, unsigned P, bool ParameterPack, IdentifierInfo *Id, TemplateNameKind ParameterKind, bool Typename, TemplateParameterList *Params)
bool isParameterPack() const
Whether this template template parameter is a template parameter pack.
unsigned getIndex() const
Get the index of the template parameter within its parameter list.
unsigned getDepth() const
Get the nesting depth of the template parameter.
Declaration of a template type parameter.
static TemplateTypeParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc, SourceLocation NameLoc, unsigned D, unsigned P, IdentifierInfo *Id, bool Typename, bool ParameterPack, bool HasTypeConstraint=false, UnsignedOrNone NumExpanded=std::nullopt)
Models the abbreviated syntax to constrain a template type parameter: template <convertible_to<string...
Definition ASTConcept.h: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:3513
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:6165
A container of type source information.
Definition TypeBase.h:8249
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:1833
bool isBlockPointerType() const
Definition TypeBase.h:8535
bool isVoidType() const
Definition TypeBase.h:8871
bool isObjCBuiltinType() const
Definition TypeBase.h:8735
QualType getRVVEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an RVV builtin type.
Definition Type.cpp:2677
bool isIncompleteArrayType() const
Definition TypeBase.h:8622
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2205
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isConstantArrayType() const
Definition TypeBase.h:8618
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:2425
bool isArrayType() const
Definition TypeBase.h:8614
bool isCharType() const
Definition Type.cpp:2132
bool isPointerType() const
Definition TypeBase.h:8515
TagDecl * castAsTagDecl() const
Definition Type.h:69
bool isArrayParameterType() const
Definition TypeBase.h:8630
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:8915
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9158
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:8955
bool isEnumeralType() const
Definition TypeBase.h:8646
bool isObjCQualifiedIdType() const
Definition TypeBase.h:8705
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:752
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:8989
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition TypeBase.h:2899
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition TypeBase.h:2790
bool isBitIntType() const
Definition TypeBase.h:8780
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8638
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2782
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:8927
bool isSaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:8943
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition TypeBase.h:2405
QualType getCanonicalTypeInternal() const
Definition TypeBase.h:3119
@ PtrdiffT
The "ptrdiff_t" type.
Definition TypeBase.h:2281
@ SizeT
The "size_t" type.
Definition TypeBase.h:2275
@ SignedSizeT
The signed integer type corresponding to "size_t".
Definition TypeBase.h:2278
bool isObjCIdType() const
Definition TypeBase.h:8717
bool isUnsaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:8951
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9144
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:2435
bool isFunctionType() const
Definition TypeBase.h:8511
bool isObjCObjectPointerType() const
Definition TypeBase.h:8684
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:8969
bool isVectorType() const
Definition TypeBase.h:8654
bool isObjCClassType() const
Definition TypeBase.h:8723
bool isRVVVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'riscv_rvv_vector_bits' type attribute,...
Definition Type.cpp:2659
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition Type.cpp:2594
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2921
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition Type.cpp:2253
bool isAnyPointerType() const
Definition TypeBase.h:8523
TypeClass getTypeClass() const
Definition TypeBase.h:2385
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition TypeBase.h:2411
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9091
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition Type.cpp:653
bool isNullPtrType() const
Definition TypeBase.h:8908
bool isRecordType() const
Definition TypeBase.h:8642
bool isObjCRetainableType() const
Definition Type.cpp:5283
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5014
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition Decl.h:3667
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition Decl.cpp:5681
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3562
QualType getUnderlyingType() const
Definition Decl.h:3617
static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TypedefNameDecl *Decl, QualType Underlying)
Definition TypeBase.h:6109
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
Definition DeclCXX.h:4455
static void Profile(llvm::FoldingSetNodeID &ID, QualType Ty, const APValue &APVal)
Definition DeclCXX.h:4483
The iterator over UnresolvedSets.
Represents the dependent type named by a dependently-scoped typename using declaration,...
Definition TypeBase.h:5970
static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const UnresolvedUsingTypenameDecl *D)
Definition TypeBase.h:6007
Represents a dependent using declaration which was marked with typename.
Definition DeclCXX.h:4037
UnresolvedUsingTypenameDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this declaration.
Definition DeclCXX.h:4102
Represents a C++ using-enum-declaration.
Definition DeclCXX.h:3792
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3399
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition DeclCXX.h:3463
BaseUsingDecl * getIntroducer() const
Gets the (written or instantiated) using declaration that introduced this declaration.
Definition DeclCXX.cpp:3374
static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const UsingShadowDecl *D, QualType UnderlyingType)
Definition TypeBase.h:6047
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:5501
void clear()
Definition Value.cpp:216
Represents a variable declaration or definition.
Definition Decl.h:926
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition Decl.cpp:2810
bool hasInit() const
Definition Decl.cpp:2398
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a static data member.
Definition Decl.cpp:2461
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1283
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:1208
bool isInline() const
Whether this variable is (C++1z) inline.
Definition Decl.h:1551
@ DeclarationOnly
This declaration is only a declaration.
Definition Decl.h:1295
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition Decl.cpp:2375
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition Decl.cpp:2779
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:3966
Expr * getSizeExpr() const
Definition TypeBase.h:3980
Represents a GCC generic vector type.
Definition TypeBase.h:4175
unsigned getNumElements() const
Definition TypeBase.h:4190
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:4199
VectorKind getVectorKind() const
Definition TypeBase.h:4195
QualType getElementType() const
Definition TypeBase.h:4189
A full comment attached to a declaration, contains block content.
Definition Comment.h:1104
ArrayRef< BlockContentComment * > getBlocks() const
Definition Comment.h:1142
const DeclInfo * getDeclInfo() const LLVM_READONLY
Definition Comment.h:1136
const Decl * getDecl() const LLVM_READONLY
Definition Comment.h:1132
Holds all information required to evaluate constexpr code in a module.
Definition Context.h:41
Defines the Linkage enumeration and various utility functions.
Defines the clang::TargetInfo interface.
Definition SPIR.cpp:47
mlir::Type getBaseType(mlir::Value varPtr)
const AstTypeMatcher< TagType > tagType
SmallVector< BoundNodes, 1 > match(MatcherT Matcher, const NodeT &Node, ASTContext &Context)
Returns the results of matching Matcher on Node.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const AstTypeMatcher< ArrayType > arrayType
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
The JSON file list parser is used to communicate input to InstallAPI.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus20
@ CPlusPlus
@ CPlusPlus17
GVALinkage
A more specific kind of linkage than enum Linkage.
Definition Linkage.h:72
@ GVA_StrongODR
Definition Linkage.h:77
@ GVA_StrongExternal
Definition Linkage.h:76
@ GVA_AvailableExternally
Definition Linkage.h:74
@ GVA_DiscardableODR
Definition Linkage.h:75
@ GVA_Internal
Definition Linkage.h:73
AutoTypeKeyword
Which keyword(s) were used to create an AutoType.
Definition TypeBase.h:1792
OpenCLTypeKind
OpenCL type kinds.
Definition TargetInfo.h:212
@ OCLTK_ReserveID
Definition TargetInfo.h:219
@ OCLTK_Sampler
Definition TargetInfo.h:220
@ OCLTK_Pipe
Definition TargetInfo.h:217
@ OCLTK_ClkEvent
Definition TargetInfo.h:214
@ OCLTK_Event
Definition TargetInfo.h:215
@ OCLTK_Default
Definition TargetInfo.h:213
@ OCLTK_Queue
Definition TargetInfo.h:218
FunctionType::ExtInfo getFunctionExtInfo(const Type &t)
Definition TypeBase.h:8413
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
NullabilityKind
Describes the nullability of a particular type.
Definition Specifiers.h:348
@ Nullable
Values of this type can be null.
Definition Specifiers.h:352
@ Unspecified
Whether values of this type can be null is (explicitly) unspecified.
Definition Specifiers.h:357
@ NonNull
Values of this type can never be null.
Definition Specifiers.h:350
@ ICIS_NoInit
No in-class initializer.
Definition Specifiers.h:272
@ TemplateName
The identifier is a template name. FIXME: Add an annotation for that.
Definition Parser.h:61
std::pair< FileID, unsigned > FileIDAndOffset
CXXABI * CreateMicrosoftCXXABI(ASTContext &Ctx)
@ Vector
'vector' clause, allowed on 'loop', Combined, and 'routine' directives.
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
TypeOfKind
The kind of 'typeof' expression we're after.
Definition TypeBase.h:918
@ AS_public
Definition Specifiers.h:124
SmallVector< Attr *, 4 > AttrVec
AttrVec - A vector of Attr, which is how they are stored on the AST.
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
@ SC_Register
Definition Specifiers.h:257
@ SC_Static
Definition Specifiers.h:252
CXXABI * CreateItaniumCXXABI(ASTContext &Ctx)
Creates an instance of a C++ ABI class.
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:3719
const FunctionProtoType * T
bool isComputedNoexcept(ExceptionSpecificationType ESpecType)
@ Template
We are parsing a template declaration.
Definition Parser.h:81
@ Interface
The "__interface" keyword.
Definition TypeBase.h:5883
@ Struct
The "struct" keyword.
Definition TypeBase.h:5880
@ Class
The "class" keyword.
Definition TypeBase.h:5889
constexpr uint16_t SelPointerConstantDiscriminator
Constant discriminator to be used with objective-c sel pointers.
bool isDiscardableGVALinkage(GVALinkage L)
Definition Linkage.h:80
BuiltinTemplateKind
Kinds of BuiltinTemplateDecl.
Definition Builtins.h:462
@ Keyword
The name has been typo-corrected to a keyword.
Definition Sema.h:560
LangAS
Defines the address space values used by the address space qualifier of QualType.
TranslationUnitKind
Describes the kind of translation unit being processed.
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:132
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:135
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition Specifiers.h:144
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:139
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1288
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:188
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition Specifiers.h:206
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition Specifiers.h:202
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:198
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:194
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition Specifiers.h:191
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:278
@ CC_M68kRTD
Definition Specifiers.h:299
@ CC_X86RegCall
Definition Specifiers.h:287
@ CC_X86VectorCall
Definition Specifiers.h:283
@ CC_X86StdCall
Definition Specifiers.h:280
@ CC_X86FastCall
Definition Specifiers.h:281
@ Invariant
The parameter is invariant: must match exactly.
Definition DeclObjC.h:555
@ Contravariant
The parameter is contravariant, e.g., X<T> is a subtype of X when the type parameter is covariant and...
Definition DeclObjC.h:563
@ Covariant
The parameter is covariant, e.g., X<T> is a subtype of X when the type parameter is covariant and T i...
Definition DeclObjC.h:559
@ AltiVecBool
is AltiVec 'vector bool ...'
Definition TypeBase.h:4145
@ SveFixedLengthData
is AArch64 SVE fixed-length data vector
Definition TypeBase.h:4154
@ AltiVecPixel
is AltiVec 'vector Pixel'
Definition TypeBase.h:4142
@ Generic
not a target-specific vector type
Definition TypeBase.h:4136
@ RVVFixedLengthData
is RISC-V RVV fixed-length data vector
Definition TypeBase.h:4160
@ RVVFixedLengthMask
is RISC-V RVV fixed-length mask vector
Definition TypeBase.h:4163
@ SveFixedLengthPredicate
is AArch64 SVE fixed-length predicate vector
Definition TypeBase.h:4157
U cast(CodeGen::Address addr)
Definition Address.h:327
LangAS getLangASFromTargetAS(unsigned TargetAS)
AlignRequirementKind
Definition ASTContext.h:176
@ None
The alignment was not explicit in code.
Definition ASTContext.h:178
@ RequiredByEnum
The alignment comes from an alignment attribute on a enum type.
Definition ASTContext.h:187
@ RequiredByTypedef
The alignment comes from an alignment attribute on a typedef.
Definition ASTContext.h:181
@ RequiredByRecord
The alignment comes from an alignment attribute on a record type.
Definition ASTContext.h:184
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition TypeBase.h:5853
@ Interface
The "__interface" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5858
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:5874
@ Struct
The "struct" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5855
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5864
@ Union
The "union" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5861
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5867
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition TypeBase.h:5871
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:6604
Expr * getCopyExpr() const
Definition Expr.h:6611
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
ArrayRef< TemplateArgument > Args
Holds information about the various types of exception specification.
Definition TypeBase.h:5311
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition TypeBase.h:5313
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition TypeBase.h:5316
Expr * NoexceptExpr
Noexcept expression, if this is a computed noexcept specification.
Definition TypeBase.h:5319
Extra information about a function prototype.
Definition TypeBase.h:5339
bool requiresFunctionProtoTypeArmAttributes() const
Definition TypeBase.h:5385
const ExtParameterInfo * ExtParameterInfos
Definition TypeBase.h:5344
bool requiresFunctionProtoTypeExtraAttributeInfo() const
Definition TypeBase.h:5389
bool requiresFunctionProtoTypeExtraBitfields() const
Definition TypeBase.h:5378
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:3258
A lazy value (of type T) that is within an AST node of type Owner, where the value might change in la...
Contains information gathered from parsing the contents of TargetAttr.
Definition TargetInfo.h:60
A std::pair-like structure for storing a qualified type split into its local qualifiers and its local...
Definition TypeBase.h:870
const Type * Ty
The locally-unqualified type.
Definition TypeBase.h:872
Qualifiers Quals
The local qualifiers.
Definition TypeBase.h:875
llvm::DenseSet< std::tuple< Decl *, Decl *, int > > NonEquivalentDeclSet
Store declaration pairs already found to be non-equivalent.
bool IsEquivalent(Decl *D1, Decl *D2)
Determine whether the two declarations are structurally equivalent.
A this pointer adjustment.
Definition Thunk.h:92
IntType
===-— Target Data Type Query Methods ----------------------------—===//
Definition TargetInfo.h:146
AlignRequirementKind AlignRequirement
Definition ASTContext.h:207
bool isAlignRequired()
Definition ASTContext.h:199
AlignRequirementKind AlignRequirement
Definition ASTContext.h:193
Information about the declaration, useful to clients of FullComment.
Definition Comment.h:983
const TemplateParameterList * TemplateParameters
Template parameters that can be referenced by \tparam if CommentDecl is a template (IsTemplateDecl or...
Definition Comment.h:1009
const Decl * CommentDecl
Declaration the comment is actually attached to (in the source).
Definition Comment.h:986