clang 20.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"
20#include "clang/AST/Attr.h"
22#include "clang/AST/CharUnits.h"
23#include "clang/AST/Comment.h"
24#include "clang/AST/Decl.h"
25#include "clang/AST/DeclBase.h"
26#include "clang/AST/DeclCXX.h"
28#include "clang/AST/DeclObjC.h"
33#include "clang/AST/Expr.h"
34#include "clang/AST/ExprCXX.h"
37#include "clang/AST/Mangle.h"
43#include "clang/AST/Stmt.h"
47#include "clang/AST/Type.h"
48#include "clang/AST/TypeLoc.h"
56#include "clang/Basic/LLVM.h"
58#include "clang/Basic/Linkage.h"
59#include "clang/Basic/Module.h"
69#include "llvm/ADT/APFixedPoint.h"
70#include "llvm/ADT/APInt.h"
71#include "llvm/ADT/APSInt.h"
72#include "llvm/ADT/ArrayRef.h"
73#include "llvm/ADT/DenseMap.h"
74#include "llvm/ADT/DenseSet.h"
75#include "llvm/ADT/FoldingSet.h"
76#include "llvm/ADT/PointerUnion.h"
77#include "llvm/ADT/STLExtras.h"
78#include "llvm/ADT/SmallPtrSet.h"
79#include "llvm/ADT/SmallVector.h"
80#include "llvm/ADT/StringExtras.h"
81#include "llvm/ADT/StringRef.h"
82#include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
83#include "llvm/Support/Capacity.h"
84#include "llvm/Support/Casting.h"
85#include "llvm/Support/Compiler.h"
86#include "llvm/Support/ErrorHandling.h"
87#include "llvm/Support/MD5.h"
88#include "llvm/Support/MathExtras.h"
89#include "llvm/Support/SipHash.h"
90#include "llvm/Support/raw_ostream.h"
91#include "llvm/TargetParser/AArch64TargetParser.h"
92#include "llvm/TargetParser/Triple.h"
93#include <algorithm>
94#include <cassert>
95#include <cstddef>
96#include <cstdint>
97#include <cstdlib>
98#include <map>
99#include <memory>
100#include <optional>
101#include <string>
102#include <tuple>
103#include <utility>
104
105using namespace clang;
106
117
118/// \returns The locations that are relevant when searching for Doc comments
119/// related to \p D.
122 assert(D);
123
124 // User can not attach documentation to implicit declarations.
125 if (D->isImplicit())
126 return {};
127
128 // User can not attach documentation to implicit instantiations.
129 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
130 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
131 return {};
132 }
133
134 if (const auto *VD = dyn_cast<VarDecl>(D)) {
135 if (VD->isStaticDataMember() &&
136 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
137 return {};
138 }
139
140 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
141 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
142 return {};
143 }
144
145 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
146 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
147 if (TSK == TSK_ImplicitInstantiation ||
148 TSK == TSK_Undeclared)
149 return {};
150 }
151
152 if (const auto *ED = dyn_cast<EnumDecl>(D)) {
153 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
154 return {};
155 }
156 if (const auto *TD = dyn_cast<TagDecl>(D)) {
157 // When tag declaration (but not definition!) is part of the
158 // decl-specifier-seq of some other declaration, it doesn't get comment
159 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
160 return {};
161 }
162 // TODO: handle comments for function parameters properly.
163 if (isa<ParmVarDecl>(D))
164 return {};
165
166 // TODO: we could look up template parameter documentation in the template
167 // documentation.
168 if (isa<TemplateTypeParmDecl>(D) ||
169 isa<NonTypeTemplateParmDecl>(D) ||
170 isa<TemplateTemplateParmDecl>(D))
171 return {};
172
174 // Find declaration location.
175 // For Objective-C declarations we generally don't expect to have multiple
176 // declarators, thus use declaration starting location as the "declaration
177 // location".
178 // For all other declarations multiple declarators are used quite frequently,
179 // so we use the location of the identifier as the "declaration location".
180 SourceLocation BaseLocation;
181 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
182 isa<ObjCPropertyDecl>(D) || isa<RedeclarableTemplateDecl>(D) ||
183 isa<ClassTemplateSpecializationDecl>(D) ||
184 // Allow association with Y across {} in `typedef struct X {} Y`.
185 isa<TypedefDecl>(D))
186 BaseLocation = D->getBeginLoc();
187 else
188 BaseLocation = D->getLocation();
189
190 if (!D->getLocation().isMacroID()) {
191 Locations.emplace_back(BaseLocation);
192 } else {
193 const auto *DeclCtx = D->getDeclContext();
194
195 // When encountering definitions generated from a macro (that are not
196 // contained by another declaration in the macro) we need to try and find
197 // the comment at the location of the expansion but if there is no comment
198 // there we should retry to see if there is a comment inside the macro as
199 // well. To this end we return first BaseLocation to first look at the
200 // expansion site, the second value is the spelling location of the
201 // beginning of the declaration defined inside the macro.
202 if (!(DeclCtx &&
203 Decl::castFromDeclContext(DeclCtx)->getLocation().isMacroID())) {
204 Locations.emplace_back(SourceMgr.getExpansionLoc(BaseLocation));
205 }
206
207 // We use Decl::getBeginLoc() and not just BaseLocation here to ensure that
208 // we don't refer to the macro argument location at the expansion site (this
209 // can happen if the name's spelling is provided via macro argument), and
210 // always to the declaration itself.
211 Locations.emplace_back(SourceMgr.getSpellingLoc(D->getBeginLoc()));
212 }
213
214 return Locations;
215}
216
218 const Decl *D, const SourceLocation RepresentativeLocForDecl,
219 const std::map<unsigned, RawComment *> &CommentsInTheFile) const {
220 // If the declaration doesn't map directly to a location in a file, we
221 // can't find the comment.
222 if (RepresentativeLocForDecl.isInvalid() ||
223 !RepresentativeLocForDecl.isFileID())
224 return nullptr;
225
226 // If there are no comments anywhere, we won't find anything.
227 if (CommentsInTheFile.empty())
228 return nullptr;
229
230 // Decompose the location for the declaration and find the beginning of the
231 // file buffer.
232 const std::pair<FileID, unsigned> DeclLocDecomp =
233 SourceMgr.getDecomposedLoc(RepresentativeLocForDecl);
234
235 // Slow path.
236 auto OffsetCommentBehindDecl =
237 CommentsInTheFile.lower_bound(DeclLocDecomp.second);
238
239 // First check whether we have a trailing comment.
240 if (OffsetCommentBehindDecl != CommentsInTheFile.end()) {
241 RawComment *CommentBehindDecl = OffsetCommentBehindDecl->second;
242 if ((CommentBehindDecl->isDocumentation() ||
243 LangOpts.CommentOpts.ParseAllComments) &&
244 CommentBehindDecl->isTrailingComment() &&
245 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
246 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
247
248 // Check that Doxygen trailing comment comes after the declaration, starts
249 // on the same line and in the same file as the declaration.
250 if (SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second) ==
251 Comments.getCommentBeginLine(CommentBehindDecl, DeclLocDecomp.first,
252 OffsetCommentBehindDecl->first)) {
253 return CommentBehindDecl;
254 }
255 }
256 }
257
258 // The comment just after the declaration was not a trailing comment.
259 // Let's look at the previous comment.
260 if (OffsetCommentBehindDecl == CommentsInTheFile.begin())
261 return nullptr;
262
263 auto OffsetCommentBeforeDecl = --OffsetCommentBehindDecl;
264 RawComment *CommentBeforeDecl = OffsetCommentBeforeDecl->second;
265
266 // Check that we actually have a non-member Doxygen comment.
267 if (!(CommentBeforeDecl->isDocumentation() ||
268 LangOpts.CommentOpts.ParseAllComments) ||
269 CommentBeforeDecl->isTrailingComment())
270 return nullptr;
271
272 // Decompose the end of the comment.
273 const unsigned CommentEndOffset =
274 Comments.getCommentEndOffset(CommentBeforeDecl);
275
276 // Get the corresponding buffer.
277 bool Invalid = false;
278 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
279 &Invalid).data();
280 if (Invalid)
281 return nullptr;
282
283 // Extract text between the comment and declaration.
284 StringRef Text(Buffer + CommentEndOffset,
285 DeclLocDecomp.second - CommentEndOffset);
286
287 // There should be no other declarations or preprocessor directives between
288 // comment and declaration.
289 if (Text.find_last_of(";{}#@") != StringRef::npos)
290 return nullptr;
291
292 return CommentBeforeDecl;
293}
294
296 const auto DeclLocs = getDeclLocsForCommentSearch(D, SourceMgr);
297
298 for (const auto DeclLoc : DeclLocs) {
299 // If the declaration doesn't map directly to a location in a file, we
300 // can't find the comment.
301 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
302 continue;
303
306 CommentsLoaded = true;
307 }
308
309 if (Comments.empty())
310 continue;
311
312 const FileID File = SourceMgr.getDecomposedLoc(DeclLoc).first;
313 if (!File.isValid())
314 continue;
315
316 const auto CommentsInThisFile = Comments.getCommentsInFile(File);
317 if (!CommentsInThisFile || CommentsInThisFile->empty())
318 continue;
319
320 if (RawComment *Comment =
321 getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile))
322 return Comment;
323 }
324
325 return nullptr;
326}
327
329 assert(LangOpts.RetainCommentsFromSystemHeaders ||
330 !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin()));
331 Comments.addComment(RC, LangOpts.CommentOpts, BumpAlloc);
332}
333
334/// If we have a 'templated' declaration for a template, adjust 'D' to
335/// refer to the actual template.
336/// If we have an implicit instantiation, adjust 'D' to refer to template.
337static const Decl &adjustDeclToTemplate(const Decl &D) {
338 if (const auto *FD = dyn_cast<FunctionDecl>(&D)) {
339 // Is this function declaration part of a function template?
340 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
341 return *FTD;
342
343 // Nothing to do if function is not an implicit instantiation.
344 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
345 return D;
346
347 // Function is an implicit instantiation of a function template?
348 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
349 return *FTD;
350
351 // Function is instantiated from a member definition of a class template?
352 if (const FunctionDecl *MemberDecl =
354 return *MemberDecl;
355
356 return D;
357 }
358 if (const auto *VD = dyn_cast<VarDecl>(&D)) {
359 // Static data member is instantiated from a member definition of a class
360 // template?
361 if (VD->isStaticDataMember())
362 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
363 return *MemberDecl;
364
365 return D;
366 }
367 if (const auto *CRD = dyn_cast<CXXRecordDecl>(&D)) {
368 // Is this class declaration part of a class template?
369 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
370 return *CTD;
371
372 // Class is an implicit instantiation of a class template or partial
373 // specialization?
374 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
375 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
376 return D;
377 llvm::PointerUnion<ClassTemplateDecl *,
380 return PU.is<ClassTemplateDecl *>()
381 ? *static_cast<const Decl *>(PU.get<ClassTemplateDecl *>())
382 : *static_cast<const Decl *>(
384 }
385
386 // Class is instantiated from a member definition of a class template?
387 if (const MemberSpecializationInfo *Info =
388 CRD->getMemberSpecializationInfo())
389 return *Info->getInstantiatedFrom();
390
391 return D;
392 }
393 if (const auto *ED = dyn_cast<EnumDecl>(&D)) {
394 // Enum is instantiated from a member definition of a class template?
395 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
396 return *MemberDecl;
397
398 return D;
399 }
400 // FIXME: Adjust alias templates?
401 return D;
402}
403
405 const Decl *D,
406 const Decl **OriginalDecl) const {
407 if (!D) {
408 if (OriginalDecl)
409 OriginalDecl = nullptr;
410 return nullptr;
411 }
412
414
415 // Any comment directly attached to D?
416 {
417 auto DeclComment = DeclRawComments.find(D);
418 if (DeclComment != DeclRawComments.end()) {
419 if (OriginalDecl)
420 *OriginalDecl = D;
421 return DeclComment->second;
422 }
423 }
424
425 // Any comment attached to any redeclaration of D?
426 const Decl *CanonicalD = D->getCanonicalDecl();
427 if (!CanonicalD)
428 return nullptr;
429
430 {
431 auto RedeclComment = RedeclChainComments.find(CanonicalD);
432 if (RedeclComment != RedeclChainComments.end()) {
433 if (OriginalDecl)
434 *OriginalDecl = RedeclComment->second;
435 auto CommentAtRedecl = DeclRawComments.find(RedeclComment->second);
436 assert(CommentAtRedecl != DeclRawComments.end() &&
437 "This decl is supposed to have comment attached.");
438 return CommentAtRedecl->second;
439 }
440 }
441
442 // Any redeclarations of D that we haven't checked for comments yet?
443 // We can't use DenseMap::iterator directly since it'd get invalid.
444 auto LastCheckedRedecl = [this, CanonicalD]() -> const Decl * {
445 return CommentlessRedeclChains.lookup(CanonicalD);
446 }();
447
448 for (const auto Redecl : D->redecls()) {
449 assert(Redecl);
450 // Skip all redeclarations that have been checked previously.
451 if (LastCheckedRedecl) {
452 if (LastCheckedRedecl == Redecl) {
453 LastCheckedRedecl = nullptr;
454 }
455 continue;
456 }
457 const RawComment *RedeclComment = getRawCommentForDeclNoCache(Redecl);
458 if (RedeclComment) {
459 cacheRawCommentForDecl(*Redecl, *RedeclComment);
460 if (OriginalDecl)
461 *OriginalDecl = Redecl;
462 return RedeclComment;
463 }
464 CommentlessRedeclChains[CanonicalD] = Redecl;
465 }
466
467 if (OriginalDecl)
468 *OriginalDecl = nullptr;
469 return nullptr;
470}
471
473 const RawComment &Comment) const {
474 assert(Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
475 DeclRawComments.try_emplace(&OriginalD, &Comment);
476 const Decl *const CanonicalDecl = OriginalD.getCanonicalDecl();
477 RedeclChainComments.try_emplace(CanonicalDecl, &OriginalD);
478 CommentlessRedeclChains.erase(CanonicalDecl);
479}
480
481static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
483 const DeclContext *DC = ObjCMethod->getDeclContext();
484 if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) {
485 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
486 if (!ID)
487 return;
488 // Add redeclared method here.
489 for (const auto *Ext : ID->known_extensions()) {
490 if (ObjCMethodDecl *RedeclaredMethod =
491 Ext->getMethod(ObjCMethod->getSelector(),
492 ObjCMethod->isInstanceMethod()))
493 Redeclared.push_back(RedeclaredMethod);
494 }
495 }
496}
497
499 const Preprocessor *PP) {
500 if (Comments.empty() || Decls.empty())
501 return;
502
503 FileID File;
504 for (const Decl *D : Decls) {
505 if (D->isInvalidDecl())
506 continue;
507
510 if (Loc.isValid()) {
511 // See if there are any new comments that are not attached to a decl.
512 // The location doesn't have to be precise - we care only about the file.
513 File = SourceMgr.getDecomposedLoc(Loc).first;
514 break;
515 }
516 }
517
518 if (File.isInvalid())
519 return;
520
521 auto CommentsInThisFile = Comments.getCommentsInFile(File);
522 if (!CommentsInThisFile || CommentsInThisFile->empty() ||
523 CommentsInThisFile->rbegin()->second->isAttached())
524 return;
525
526 // There is at least one comment not attached to a decl.
527 // Maybe it should be attached to one of Decls?
528 //
529 // Note that this way we pick up not only comments that precede the
530 // declaration, but also comments that *follow* the declaration -- thanks to
531 // the lookahead in the lexer: we've consumed the semicolon and looked
532 // ahead through comments.
533 for (const Decl *D : Decls) {
534 assert(D);
535 if (D->isInvalidDecl())
536 continue;
537
539
540 if (DeclRawComments.count(D) > 0)
541 continue;
542
543 const auto DeclLocs = getDeclLocsForCommentSearch(D, SourceMgr);
544
545 for (const auto DeclLoc : DeclLocs) {
546 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
547 continue;
548
549 if (RawComment *const DocComment = getRawCommentForDeclNoCacheImpl(
550 D, DeclLoc, *CommentsInThisFile)) {
551 cacheRawCommentForDecl(*D, *DocComment);
552 comments::FullComment *FC = DocComment->parse(*this, PP, D);
554 break;
555 }
556 }
557 }
558}
559
561 const Decl *D) const {
562 auto *ThisDeclInfo = new (*this) comments::DeclInfo;
563 ThisDeclInfo->CommentDecl = D;
564 ThisDeclInfo->IsFilled = false;
565 ThisDeclInfo->fill();
566 ThisDeclInfo->CommentDecl = FC->getDecl();
567 if (!ThisDeclInfo->TemplateParameters)
568 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
570 new (*this) comments::FullComment(FC->getBlocks(),
571 ThisDeclInfo);
572 return CFC;
573}
574
577 return RC ? RC->parse(*this, nullptr, D) : nullptr;
578}
579
581 const Decl *D,
582 const Preprocessor *PP) const {
583 if (!D || D->isInvalidDecl())
584 return nullptr;
586
587 const Decl *Canonical = D->getCanonicalDecl();
588 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
589 ParsedComments.find(Canonical);
590
591 if (Pos != ParsedComments.end()) {
592 if (Canonical != D) {
593 comments::FullComment *FC = Pos->second;
595 return CFC;
596 }
597 return Pos->second;
598 }
599
600 const Decl *OriginalDecl = nullptr;
601
602 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
603 if (!RC) {
604 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
606 const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
607 if (OMD && OMD->isPropertyAccessor())
608 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
609 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
610 return cloneFullComment(FC, D);
611 if (OMD)
612 addRedeclaredMethods(OMD, Overridden);
613 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
614 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
615 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
616 return cloneFullComment(FC, D);
617 }
618 else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
619 // Attach any tag type's documentation to its typedef if latter
620 // does not have one of its own.
621 QualType QT = TD->getUnderlyingType();
622 if (const auto *TT = QT->getAs<TagType>())
623 if (const Decl *TD = TT->getDecl())
625 return cloneFullComment(FC, D);
626 }
627 else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
628 while (IC->getSuperClass()) {
629 IC = IC->getSuperClass();
631 return cloneFullComment(FC, D);
632 }
633 }
634 else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) {
635 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
637 return cloneFullComment(FC, D);
638 }
639 else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
640 if (!(RD = RD->getDefinition()))
641 return nullptr;
642 // Check non-virtual bases.
643 for (const auto &I : RD->bases()) {
644 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
645 continue;
646 QualType Ty = I.getType();
647 if (Ty.isNull())
648 continue;
650 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
651 continue;
652
654 return cloneFullComment(FC, D);
655 }
656 }
657 // Check virtual bases.
658 for (const auto &I : RD->vbases()) {
659 if (I.getAccessSpecifier() != AS_public)
660 continue;
661 QualType Ty = I.getType();
662 if (Ty.isNull())
663 continue;
664 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
665 if (!(VirtualBase= VirtualBase->getDefinition()))
666 continue;
668 return cloneFullComment(FC, D);
669 }
670 }
671 }
672 return nullptr;
673 }
674
675 // If the RawComment was attached to other redeclaration of this Decl, we
676 // should parse the comment in context of that other Decl. This is important
677 // because comments can contain references to parameter names which can be
678 // different across redeclarations.
679 if (D != OriginalDecl && OriginalDecl)
680 return getCommentForDecl(OriginalDecl, PP);
681
682 comments::FullComment *FC = RC->parse(*this, PP, D);
683 ParsedComments[Canonical] = FC;
684 return FC;
685}
686
687void
688ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
689 const ASTContext &C,
691 ID.AddInteger(Parm->getDepth());
692 ID.AddInteger(Parm->getPosition());
693 ID.AddBoolean(Parm->isParameterPack());
694
696 ID.AddInteger(Params->size());
698 PEnd = Params->end();
699 P != PEnd; ++P) {
700 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
701 ID.AddInteger(0);
702 ID.AddBoolean(TTP->isParameterPack());
703 if (TTP->isExpandedParameterPack()) {
704 ID.AddBoolean(true);
705 ID.AddInteger(TTP->getNumExpansionParameters());
706 } else
707 ID.AddBoolean(false);
708 continue;
709 }
710
711 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
712 ID.AddInteger(1);
713 ID.AddBoolean(NTTP->isParameterPack());
714 ID.AddPointer(C.getUnconstrainedType(C.getCanonicalType(NTTP->getType()))
715 .getAsOpaquePtr());
716 if (NTTP->isExpandedParameterPack()) {
717 ID.AddBoolean(true);
718 ID.AddInteger(NTTP->getNumExpansionTypes());
719 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
720 QualType T = NTTP->getExpansionType(I);
721 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
722 }
723 } else
724 ID.AddBoolean(false);
725 continue;
726 }
727
728 auto *TTP = cast<TemplateTemplateParmDecl>(*P);
729 ID.AddInteger(2);
730 Profile(ID, C, TTP);
731 }
732}
733
735ASTContext::getCanonicalTemplateTemplateParmDecl(
736 TemplateTemplateParmDecl *TTP) const {
737 // Check if we already have a canonical template template parameter.
738 llvm::FoldingSetNodeID ID;
739 CanonicalTemplateTemplateParm::Profile(ID, *this, TTP);
740 void *InsertPos = nullptr;
741 CanonicalTemplateTemplateParm *Canonical
742 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
743 if (Canonical)
744 return Canonical->getParam();
745
746 // Build a canonical template parameter list.
748 SmallVector<NamedDecl *, 4> CanonParams;
749 CanonParams.reserve(Params->size());
751 PEnd = Params->end();
752 P != PEnd; ++P) {
753 // Note that, per C++20 [temp.over.link]/6, when determining whether
754 // template-parameters are equivalent, constraints are ignored.
755 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
758 TTP->getDepth(), TTP->getIndex(), nullptr, false,
759 TTP->isParameterPack(), /*HasTypeConstraint=*/false,
761 ? std::optional<unsigned>(TTP->getNumExpansionParameters())
762 : std::nullopt);
763 CanonParams.push_back(NewTTP);
764 } else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
768 if (NTTP->isExpandedParameterPack()) {
769 SmallVector<QualType, 2> ExpandedTypes;
771 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
772 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
773 ExpandedTInfos.push_back(
774 getTrivialTypeSourceInfo(ExpandedTypes.back()));
775 }
776
780 NTTP->getDepth(),
781 NTTP->getPosition(), nullptr,
782 T,
783 TInfo,
784 ExpandedTypes,
785 ExpandedTInfos);
786 } else {
790 NTTP->getDepth(),
791 NTTP->getPosition(), nullptr,
792 T,
793 NTTP->isParameterPack(),
794 TInfo);
795 }
796 CanonParams.push_back(Param);
797 } else
798 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
799 cast<TemplateTemplateParmDecl>(*P)));
800 }
801
804 TTP->getPosition(), TTP->isParameterPack(), nullptr, /*Typename=*/false,
806 CanonParams, SourceLocation(),
807 /*RequiresClause=*/nullptr));
808
809 // Get the new insert position for the node we care about.
810 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
811 assert(!Canonical && "Shouldn't be in the map!");
812 (void)Canonical;
813
814 // Create the canonical template template parameter entry.
815 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
816 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
817 return CanonTTP;
818}
819
821 auto Kind = getTargetInfo().getCXXABI().getKind();
822 return getLangOpts().CXXABI.value_or(Kind);
823}
824
825CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
826 if (!LangOpts.CPlusPlus) return nullptr;
827
828 switch (getCXXABIKind()) {
829 case TargetCXXABI::AppleARM64:
830 case TargetCXXABI::Fuchsia:
831 case TargetCXXABI::GenericARM: // Same as Itanium at this level
832 case TargetCXXABI::iOS:
833 case TargetCXXABI::WatchOS:
834 case TargetCXXABI::GenericAArch64:
835 case TargetCXXABI::GenericMIPS:
836 case TargetCXXABI::GenericItanium:
837 case TargetCXXABI::WebAssembly:
838 case TargetCXXABI::XL:
839 return CreateItaniumCXXABI(*this);
840 case TargetCXXABI::Microsoft:
841 return CreateMicrosoftCXXABI(*this);
842 }
843 llvm_unreachable("Invalid CXXABI type!");
844}
845
847 if (!InterpContext) {
848 InterpContext.reset(new interp::Context(*this));
849 }
850 return *InterpContext.get();
851}
852
854 if (!ParentMapCtx)
855 ParentMapCtx.reset(new ParentMapContext(*this));
856 return *ParentMapCtx.get();
857}
858
860 const LangOptions &LangOpts) {
861 switch (LangOpts.getAddressSpaceMapMangling()) {
863 return TI.useAddressSpaceMapMangling();
865 return true;
867 return false;
868 }
869 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
870}
871
873 IdentifierTable &idents, SelectorTable &sels,
874 Builtin::Context &builtins, TranslationUnitKind TUKind)
875 : ConstantArrayTypes(this_(), ConstantArrayTypesLog2InitSize),
876 DependentSizedArrayTypes(this_()), DependentSizedExtVectorTypes(this_()),
877 DependentAddressSpaceTypes(this_()), DependentVectorTypes(this_()),
878 DependentSizedMatrixTypes(this_()),
879 FunctionProtoTypes(this_(), FunctionProtoTypesLog2InitSize),
880 DependentTypeOfExprTypes(this_()), DependentDecltypeTypes(this_()),
881 TemplateSpecializationTypes(this_()),
882 DependentTemplateSpecializationTypes(this_()), AutoTypes(this_()),
883 DependentBitIntTypes(this_()), SubstTemplateTemplateParmPacks(this_()),
884 ArrayParameterTypes(this_()), CanonTemplateTemplateParms(this_()),
885 SourceMgr(SM), LangOpts(LOpts),
886 NoSanitizeL(new NoSanitizeList(LangOpts.NoSanitizeFiles, SM)),
887 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
888 LangOpts.XRayNeverInstrumentFiles,
889 LangOpts.XRayAttrListFiles, SM)),
890 ProfList(new ProfileList(LangOpts.ProfileListFiles, SM)),
891 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
892 BuiltinInfo(builtins), TUKind(TUKind), DeclarationNames(*this),
893 Comments(SM), CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
894 CompCategories(this_()), LastSDM(nullptr, 0) {
896}
897
899 // Release the DenseMaps associated with DeclContext objects.
900 // FIXME: Is this the ideal solution?
901 ReleaseDeclContextMaps();
902
903 // Call all of the deallocation functions on all of their targets.
904 for (auto &Pair : Deallocations)
905 (Pair.first)(Pair.second);
906 Deallocations.clear();
907
908 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
909 // because they can contain DenseMaps.
910 for (llvm::DenseMap<const ObjCContainerDecl*,
911 const ASTRecordLayout*>::iterator
912 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
913 // Increment in loop to prevent using deallocated memory.
914 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
915 R->Destroy(*this);
916 ObjCLayouts.clear();
917
918 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
919 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
920 // Increment in loop to prevent using deallocated memory.
921 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
922 R->Destroy(*this);
923 }
924 ASTRecordLayouts.clear();
925
926 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
927 AEnd = DeclAttrs.end();
928 A != AEnd; ++A)
929 A->second->~AttrVec();
930 DeclAttrs.clear();
931
932 for (const auto &Value : ModuleInitializers)
933 Value.second->~PerModuleInitializers();
934 ModuleInitializers.clear();
935}
936
938
939void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
940 TraversalScope = TopLevelDecls;
942}
943
944void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const {
945 Deallocations.push_back({Callback, Data});
946}
947
948void
950 ExternalSource = std::move(Source);
951}
952
954 llvm::errs() << "\n*** AST Context Stats:\n";
955 llvm::errs() << " " << Types.size() << " types total.\n";
956
957 unsigned counts[] = {
958#define TYPE(Name, Parent) 0,
959#define ABSTRACT_TYPE(Name, Parent)
960#include "clang/AST/TypeNodes.inc"
961 0 // Extra
962 };
963
964 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
965 Type *T = Types[i];
966 counts[(unsigned)T->getTypeClass()]++;
967 }
968
969 unsigned Idx = 0;
970 unsigned TotalBytes = 0;
971#define TYPE(Name, Parent) \
972 if (counts[Idx]) \
973 llvm::errs() << " " << counts[Idx] << " " << #Name \
974 << " types, " << sizeof(Name##Type) << " each " \
975 << "(" << counts[Idx] * sizeof(Name##Type) \
976 << " bytes)\n"; \
977 TotalBytes += counts[Idx] * sizeof(Name##Type); \
978 ++Idx;
979#define ABSTRACT_TYPE(Name, Parent)
980#include "clang/AST/TypeNodes.inc"
981
982 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
983
984 // Implicit special member functions.
985 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
987 << " implicit default constructors created\n";
988 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
990 << " implicit copy constructors created\n";
992 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
994 << " implicit move constructors created\n";
995 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
997 << " implicit copy assignment operators created\n";
999 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
1001 << " implicit move assignment operators created\n";
1002 llvm::errs() << NumImplicitDestructorsDeclared << "/"
1004 << " implicit destructors created\n";
1005
1006 if (ExternalSource) {
1007 llvm::errs() << "\n";
1009 }
1010
1011 BumpAlloc.PrintStats();
1012}
1013
1015 bool NotifyListeners) {
1016 if (NotifyListeners)
1017 if (auto *Listener = getASTMutationListener())
1019
1020 MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M);
1021}
1022
1024 auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl()));
1025 if (It == MergedDefModules.end())
1026 return;
1027
1028 auto &Merged = It->second;
1029 llvm::DenseSet<Module*> Found;
1030 for (Module *&M : Merged)
1031 if (!Found.insert(M).second)
1032 M = nullptr;
1033 llvm::erase(Merged, nullptr);
1034}
1035
1038 auto MergedIt =
1039 MergedDefModules.find(cast<NamedDecl>(Def->getCanonicalDecl()));
1040 if (MergedIt == MergedDefModules.end())
1041 return std::nullopt;
1042 return MergedIt->second;
1043}
1044
1045void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
1046 if (LazyInitializers.empty())
1047 return;
1048
1049 auto *Source = Ctx.getExternalSource();
1050 assert(Source && "lazy initializers but no external source");
1051
1052 auto LazyInits = std::move(LazyInitializers);
1053 LazyInitializers.clear();
1054
1055 for (auto ID : LazyInits)
1056 Initializers.push_back(Source->GetExternalDecl(ID));
1057
1058 assert(LazyInitializers.empty() &&
1059 "GetExternalDecl for lazy module initializer added more inits");
1060}
1061
1063 // One special case: if we add a module initializer that imports another
1064 // module, and that module's only initializer is an ImportDecl, simplify.
1065 if (const auto *ID = dyn_cast<ImportDecl>(D)) {
1066 auto It = ModuleInitializers.find(ID->getImportedModule());
1067
1068 // Maybe the ImportDecl does nothing at all. (Common case.)
1069 if (It == ModuleInitializers.end())
1070 return;
1071
1072 // Maybe the ImportDecl only imports another ImportDecl.
1073 auto &Imported = *It->second;
1074 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
1075 Imported.resolve(*this);
1076 auto *OnlyDecl = Imported.Initializers.front();
1077 if (isa<ImportDecl>(OnlyDecl))
1078 D = OnlyDecl;
1079 }
1080 }
1081
1082 auto *&Inits = ModuleInitializers[M];
1083 if (!Inits)
1084 Inits = new (*this) PerModuleInitializers;
1085 Inits->Initializers.push_back(D);
1086}
1087
1090 auto *&Inits = ModuleInitializers[M];
1091 if (!Inits)
1092 Inits = new (*this) PerModuleInitializers;
1093 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
1094 IDs.begin(), IDs.end());
1095}
1096
1098 auto It = ModuleInitializers.find(M);
1099 if (It == ModuleInitializers.end())
1100 return std::nullopt;
1101
1102 auto *Inits = It->second;
1103 Inits->resolve(*this);
1104 return Inits->Initializers;
1105}
1106
1108 assert(M->isNamedModule());
1109 assert(!CurrentCXXNamedModule &&
1110 "We should set named module for ASTContext for only once");
1111 CurrentCXXNamedModule = M;
1112}
1113
1114bool ASTContext::isInSameModule(const Module *M1, const Module *M2) {
1115 if (!M1 != !M2)
1116 return false;
1117
1118 /// Get the representative module for M. The representative module is the
1119 /// first module unit for a specific primary module name. So that the module
1120 /// units have the same representative module belongs to the same module.
1121 ///
1122 /// The process is helpful to reduce the expensive string operations.
1123 auto GetRepresentativeModule = [this](const Module *M) {
1124 auto Iter = SameModuleLookupSet.find(M);
1125 if (Iter != SameModuleLookupSet.end())
1126 return Iter->second;
1127
1128 const Module *RepresentativeModule =
1129 PrimaryModuleNameMap.try_emplace(M->getPrimaryModuleInterfaceName(), M)
1130 .first->second;
1131 SameModuleLookupSet[M] = RepresentativeModule;
1132 return RepresentativeModule;
1133 };
1134
1135 assert(M1 && "Shouldn't call `isInSameModule` if both M1 and M2 are none.");
1136 return GetRepresentativeModule(M1) == GetRepresentativeModule(M2);
1137}
1138
1140 if (!ExternCContext)
1141 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1142
1143 return ExternCContext;
1144}
1145
1148 const IdentifierInfo *II) const {
1149 auto *BuiltinTemplate =
1151 BuiltinTemplate->setImplicit();
1152 getTranslationUnitDecl()->addDecl(BuiltinTemplate);
1153
1154 return BuiltinTemplate;
1155}
1156
1159 if (!MakeIntegerSeqDecl)
1162 return MakeIntegerSeqDecl;
1163}
1164
1167 if (!TypePackElementDecl)
1170 return TypePackElementDecl;
1171}
1172
1174 RecordDecl::TagKind TK) const {
1176 RecordDecl *NewDecl;
1177 if (getLangOpts().CPlusPlus)
1178 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1179 Loc, &Idents.get(Name));
1180 else
1181 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1182 &Idents.get(Name));
1183 NewDecl->setImplicit();
1184 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1185 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
1186 return NewDecl;
1187}
1188
1190 StringRef Name) const {
1193 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1194 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1195 NewDecl->setImplicit();
1196 return NewDecl;
1197}
1198
1200 if (!Int128Decl)
1201 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
1202 return Int128Decl;
1203}
1204
1206 if (!UInt128Decl)
1207 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
1208 return UInt128Decl;
1209}
1210
1211void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
1212 auto *Ty = new (*this, alignof(BuiltinType)) BuiltinType(K);
1214 Types.push_back(Ty);
1215}
1216
1218 const TargetInfo *AuxTarget) {
1219 assert((!this->Target || this->Target == &Target) &&
1220 "Incorrect target reinitialization");
1221 assert(VoidTy.isNull() && "Context reinitialized?");
1222
1223 this->Target = &Target;
1224 this->AuxTarget = AuxTarget;
1225
1226 ABI.reset(createCXXABI(Target));
1227 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
1228
1229 // C99 6.2.5p19.
1230 InitBuiltinType(VoidTy, BuiltinType::Void);
1231
1232 // C99 6.2.5p2.
1233 InitBuiltinType(BoolTy, BuiltinType::Bool);
1234 // C99 6.2.5p3.
1235 if (LangOpts.CharIsSigned)
1236 InitBuiltinType(CharTy, BuiltinType::Char_S);
1237 else
1238 InitBuiltinType(CharTy, BuiltinType::Char_U);
1239 // C99 6.2.5p4.
1240 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1241 InitBuiltinType(ShortTy, BuiltinType::Short);
1242 InitBuiltinType(IntTy, BuiltinType::Int);
1243 InitBuiltinType(LongTy, BuiltinType::Long);
1244 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
1245
1246 // C99 6.2.5p6.
1247 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1248 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1249 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1250 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1251 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
1252
1253 // C99 6.2.5p10.
1254 InitBuiltinType(FloatTy, BuiltinType::Float);
1255 InitBuiltinType(DoubleTy, BuiltinType::Double);
1256 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
1257
1258 // GNU extension, __float128 for IEEE quadruple precision
1259 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1260
1261 // __ibm128 for IBM extended precision
1262 InitBuiltinType(Ibm128Ty, BuiltinType::Ibm128);
1263
1264 // C11 extension ISO/IEC TS 18661-3
1265 InitBuiltinType(Float16Ty, BuiltinType::Float16);
1266
1267 // ISO/IEC JTC1 SC22 WG14 N1169 Extension
1268 InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum);
1269 InitBuiltinType(AccumTy, BuiltinType::Accum);
1270 InitBuiltinType(LongAccumTy, BuiltinType::LongAccum);
1271 InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum);
1272 InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum);
1273 InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum);
1274 InitBuiltinType(ShortFractTy, BuiltinType::ShortFract);
1275 InitBuiltinType(FractTy, BuiltinType::Fract);
1276 InitBuiltinType(LongFractTy, BuiltinType::LongFract);
1277 InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract);
1278 InitBuiltinType(UnsignedFractTy, BuiltinType::UFract);
1279 InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract);
1280 InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum);
1281 InitBuiltinType(SatAccumTy, BuiltinType::SatAccum);
1282 InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum);
1283 InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
1284 InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum);
1285 InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum);
1286 InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract);
1287 InitBuiltinType(SatFractTy, BuiltinType::SatFract);
1288 InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract);
1289 InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
1290 InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract);
1291 InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract);
1292
1293 // GNU extension, 128-bit integers.
1294 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1295 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1296
1297 // C++ 3.9.1p5
1298 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1299 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1300 else // -fshort-wchar makes wchar_t be unsigned.
1301 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1302 if (LangOpts.CPlusPlus && LangOpts.WChar)
1304 else {
1305 // C99 (or C++ using -fno-wchar).
1306 WideCharTy = getFromTargetType(Target.getWCharType());
1307 }
1308
1309 WIntTy = getFromTargetType(Target.getWIntType());
1310
1311 // C++20 (proposed)
1312 InitBuiltinType(Char8Ty, BuiltinType::Char8);
1313
1314 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1315 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1316 else // C99
1317 Char16Ty = getFromTargetType(Target.getChar16Type());
1318
1319 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1320 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1321 else // C99
1322 Char32Ty = getFromTargetType(Target.getChar32Type());
1323
1324 // Placeholder type for type-dependent expressions whose type is
1325 // completely unknown. No code should ever check a type against
1326 // DependentTy and users should never see it; however, it is here to
1327 // help diagnose failures to properly check for type-dependent
1328 // expressions.
1329 InitBuiltinType(DependentTy, BuiltinType::Dependent);
1330
1331 // Placeholder type for functions.
1332 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1333
1334 // Placeholder type for bound members.
1335 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1336
1337 // Placeholder type for unresolved templates.
1338 InitBuiltinType(UnresolvedTemplateTy, BuiltinType::UnresolvedTemplate);
1339
1340 // Placeholder type for pseudo-objects.
1341 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1342
1343 // "any" type; useful for debugger-like clients.
1344 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1345
1346 // Placeholder type for unbridged ARC casts.
1347 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1348
1349 // Placeholder type for builtin functions.
1350 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1351
1352 // Placeholder type for OMP array sections.
1353 if (LangOpts.OpenMP) {
1354 InitBuiltinType(ArraySectionTy, BuiltinType::ArraySection);
1355 InitBuiltinType(OMPArrayShapingTy, BuiltinType::OMPArrayShaping);
1356 InitBuiltinType(OMPIteratorTy, BuiltinType::OMPIterator);
1357 }
1358 // Placeholder type for OpenACC array sections, if we are ALSO in OMP mode,
1359 // don't bother, as we're just using the same type as OMP.
1360 if (LangOpts.OpenACC && !LangOpts.OpenMP) {
1361 InitBuiltinType(ArraySectionTy, BuiltinType::ArraySection);
1362 }
1363 if (LangOpts.MatrixTypes)
1364 InitBuiltinType(IncompleteMatrixIdxTy, BuiltinType::IncompleteMatrixIdx);
1365
1366 // Builtin types for 'id', 'Class', and 'SEL'.
1367 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1368 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
1369 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
1370
1371 if (LangOpts.OpenCL) {
1372#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1373 InitBuiltinType(SingletonId, BuiltinType::Id);
1374#include "clang/Basic/OpenCLImageTypes.def"
1375
1376 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
1377 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
1378 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1379 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1380 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
1381
1382#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1383 InitBuiltinType(Id##Ty, BuiltinType::Id);
1384#include "clang/Basic/OpenCLExtensionTypes.def"
1385 }
1386
1387 if (LangOpts.HLSL) {
1388#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
1389 InitBuiltinType(SingletonId, BuiltinType::Id);
1390#include "clang/Basic/HLSLIntangibleTypes.def"
1391 }
1392
1393 if (Target.hasAArch64SVETypes() ||
1394 (AuxTarget && AuxTarget->hasAArch64SVETypes())) {
1395#define SVE_TYPE(Name, Id, SingletonId) \
1396 InitBuiltinType(SingletonId, BuiltinType::Id);
1397#include "clang/Basic/AArch64SVEACLETypes.def"
1398 }
1399
1400 if (Target.getTriple().isPPC64()) {
1401#define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
1402 InitBuiltinType(Id##Ty, BuiltinType::Id);
1403#include "clang/Basic/PPCTypes.def"
1404#define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
1405 InitBuiltinType(Id##Ty, BuiltinType::Id);
1406#include "clang/Basic/PPCTypes.def"
1407 }
1408
1409 if (Target.hasRISCVVTypes()) {
1410#define RVV_TYPE(Name, Id, SingletonId) \
1411 InitBuiltinType(SingletonId, BuiltinType::Id);
1412#include "clang/Basic/RISCVVTypes.def"
1413 }
1414
1415 if (Target.getTriple().isWasm() && Target.hasFeature("reference-types")) {
1416#define WASM_TYPE(Name, Id, SingletonId) \
1417 InitBuiltinType(SingletonId, BuiltinType::Id);
1418#include "clang/Basic/WebAssemblyReferenceTypes.def"
1419 }
1420
1421 if (Target.getTriple().isAMDGPU() ||
1422 (AuxTarget && AuxTarget->getTriple().isAMDGPU())) {
1423#define AMDGPU_TYPE(Name, Id, SingletonId) \
1424 InitBuiltinType(SingletonId, BuiltinType::Id);
1425#include "clang/Basic/AMDGPUTypes.def"
1426 }
1427
1428 // Builtin type for __objc_yes and __objc_no
1429 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1431
1432 ObjCConstantStringType = QualType();
1433
1434 ObjCSuperType = QualType();
1435
1436 // void * type
1437 if (LangOpts.OpenCLGenericAddressSpace) {
1438 auto Q = VoidTy.getQualifiers();
1442 } else {
1444 }
1445
1446 // nullptr type (C++0x 2.14.7)
1447 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
1448
1449 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1450 InitBuiltinType(HalfTy, BuiltinType::Half);
1451
1452 InitBuiltinType(BFloat16Ty, BuiltinType::BFloat16);
1453
1454 // Builtin type used to help define __builtin_va_list.
1455 VaListTagDecl = nullptr;
1456
1457 // MSVC predeclares struct _GUID, and we need it to create MSGuidDecls.
1458 if (LangOpts.MicrosoftExt || LangOpts.Borland) {
1461 }
1462}
1463
1465 return SourceMgr.getDiagnostics();
1466}
1467
1469 AttrVec *&Result = DeclAttrs[D];
1470 if (!Result) {
1471 void *Mem = Allocate(sizeof(AttrVec));
1472 Result = new (Mem) AttrVec;
1473 }
1474
1475 return *Result;
1476}
1477
1478/// Erase the attributes corresponding to the given declaration.
1480 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1481 if (Pos != DeclAttrs.end()) {
1482 Pos->second->~AttrVec();
1483 DeclAttrs.erase(Pos);
1484 }
1485}
1486
1487// FIXME: Remove ?
1490 assert(Var->isStaticDataMember() && "Not a static data member");
1492 .dyn_cast<MemberSpecializationInfo *>();
1493}
1494
1497 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1498 TemplateOrInstantiation.find(Var);
1499 if (Pos == TemplateOrInstantiation.end())
1500 return {};
1501
1502 return Pos->second;
1503}
1504
1505void
1508 SourceLocation PointOfInstantiation) {
1509 assert(Inst->isStaticDataMember() && "Not a static data member");
1510 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1512 Tmpl, TSK, PointOfInstantiation));
1513}
1514
1515void
1518 assert(!TemplateOrInstantiation[Inst] &&
1519 "Already noted what the variable was instantiated from");
1520 TemplateOrInstantiation[Inst] = TSI;
1521}
1522
1523NamedDecl *
1525 return InstantiatedFromUsingDecl.lookup(UUD);
1526}
1527
1528void
1530 assert((isa<UsingDecl>(Pattern) ||
1531 isa<UnresolvedUsingValueDecl>(Pattern) ||
1532 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1533 "pattern decl is not a using decl");
1534 assert((isa<UsingDecl>(Inst) ||
1535 isa<UnresolvedUsingValueDecl>(Inst) ||
1536 isa<UnresolvedUsingTypenameDecl>(Inst)) &&
1537 "instantiation did not produce a using decl");
1538 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1539 InstantiatedFromUsingDecl[Inst] = Pattern;
1540}
1541
1544 return InstantiatedFromUsingEnumDecl.lookup(UUD);
1545}
1546
1548 UsingEnumDecl *Pattern) {
1549 assert(!InstantiatedFromUsingEnumDecl[Inst] && "pattern already exists");
1550 InstantiatedFromUsingEnumDecl[Inst] = Pattern;
1551}
1552
1555 return InstantiatedFromUsingShadowDecl.lookup(Inst);
1556}
1557
1558void
1560 UsingShadowDecl *Pattern) {
1561 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1562 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1563}
1564
1566 return InstantiatedFromUnnamedFieldDecl.lookup(Field);
1567}
1568
1570 FieldDecl *Tmpl) {
1571 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1572 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1573 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1574 "Already noted what unnamed field was instantiated from");
1575
1576 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1577}
1578
1581 return overridden_methods(Method).begin();
1582}
1583
1586 return overridden_methods(Method).end();
1587}
1588
1589unsigned
1591 auto Range = overridden_methods(Method);
1592 return Range.end() - Range.begin();
1593}
1594
1597 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1598 OverriddenMethods.find(Method->getCanonicalDecl());
1599 if (Pos == OverriddenMethods.end())
1600 return overridden_method_range(nullptr, nullptr);
1601 return overridden_method_range(Pos->second.begin(), Pos->second.end());
1602}
1603
1605 const CXXMethodDecl *Overridden) {
1606 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1607 OverriddenMethods[Method].push_back(Overridden);
1608}
1609
1611 const NamedDecl *D,
1612 SmallVectorImpl<const NamedDecl *> &Overridden) const {
1613 assert(D);
1614
1615 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1616 Overridden.append(overridden_methods_begin(CXXMethod),
1617 overridden_methods_end(CXXMethod));
1618 return;
1619 }
1620
1621 const auto *Method = dyn_cast<ObjCMethodDecl>(D);
1622 if (!Method)
1623 return;
1624
1626 Method->getOverriddenMethods(OverDecls);
1627 Overridden.append(OverDecls.begin(), OverDecls.end());
1628}
1629
1631 assert(!Import->getNextLocalImport() &&
1632 "Import declaration already in the chain");
1633 assert(!Import->isFromASTFile() && "Non-local import declaration");
1634 if (!FirstLocalImport) {
1635 FirstLocalImport = Import;
1636 LastLocalImport = Import;
1637 return;
1638 }
1639
1640 LastLocalImport->setNextLocalImport(Import);
1641 LastLocalImport = Import;
1642}
1643
1644//===----------------------------------------------------------------------===//
1645// Type Sizing and Analysis
1646//===----------------------------------------------------------------------===//
1647
1648/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1649/// scalar floating point type.
1650const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1651 switch (T->castAs<BuiltinType>()->getKind()) {
1652 default:
1653 llvm_unreachable("Not a floating point type!");
1654 case BuiltinType::BFloat16:
1655 return Target->getBFloat16Format();
1656 case BuiltinType::Float16:
1657 return Target->getHalfFormat();
1658 case BuiltinType::Half:
1659 return Target->getHalfFormat();
1660 case BuiltinType::Float: return Target->getFloatFormat();
1661 case BuiltinType::Double: return Target->getDoubleFormat();
1662 case BuiltinType::Ibm128:
1663 return Target->getIbm128Format();
1664 case BuiltinType::LongDouble:
1665 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1666 return AuxTarget->getLongDoubleFormat();
1667 return Target->getLongDoubleFormat();
1668 case BuiltinType::Float128:
1669 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1670 return AuxTarget->getFloat128Format();
1671 return Target->getFloat128Format();
1672 }
1673}
1674
1675CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1676 unsigned Align = Target->getCharWidth();
1677
1678 const unsigned AlignFromAttr = D->getMaxAlignment();
1679 if (AlignFromAttr)
1680 Align = AlignFromAttr;
1681
1682 // __attribute__((aligned)) can increase or decrease alignment
1683 // *except* on a struct or struct member, where it only increases
1684 // alignment unless 'packed' is also specified.
1685 //
1686 // It is an error for alignas to decrease alignment, so we can
1687 // ignore that possibility; Sema should diagnose it.
1688 bool UseAlignAttrOnly;
1689 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D))
1690 UseAlignAttrOnly =
1691 FD->hasAttr<PackedAttr>() || FD->getParent()->hasAttr<PackedAttr>();
1692 else
1693 UseAlignAttrOnly = AlignFromAttr != 0;
1694 // If we're using the align attribute only, just ignore everything
1695 // else about the declaration and its type.
1696 if (UseAlignAttrOnly) {
1697 // do nothing
1698 } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
1699 QualType T = VD->getType();
1700 if (const auto *RT = T->getAs<ReferenceType>()) {
1701 if (ForAlignof)
1702 T = RT->getPointeeType();
1703 else
1704 T = getPointerType(RT->getPointeeType());
1705 }
1706 QualType BaseT = getBaseElementType(T);
1707 if (T->isFunctionType())
1708 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1709 else if (!BaseT->isIncompleteType()) {
1710 // Adjust alignments of declarations with array type by the
1711 // large-array alignment on the target.
1712 if (const ArrayType *arrayType = getAsArrayType(T)) {
1713 unsigned MinWidth = Target->getLargeArrayMinWidth();
1714 if (!ForAlignof && MinWidth) {
1715 if (isa<VariableArrayType>(arrayType))
1716 Align = std::max(Align, Target->getLargeArrayAlign());
1717 else if (isa<ConstantArrayType>(arrayType) &&
1718 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1719 Align = std::max(Align, Target->getLargeArrayAlign());
1720 }
1721 }
1722 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1723 if (BaseT.getQualifiers().hasUnaligned())
1724 Align = Target->getCharWidth();
1725 }
1726
1727 // Ensure miminum alignment for global variables.
1728 if (const auto *VD = dyn_cast<VarDecl>(D))
1729 if (VD->hasGlobalStorage() && !ForAlignof) {
1730 uint64_t TypeSize =
1731 !BaseT->isIncompleteType() ? getTypeSize(T.getTypePtr()) : 0;
1732 Align = std::max(Align, getMinGlobalAlignOfVar(TypeSize, VD));
1733 }
1734
1735 // Fields can be subject to extra alignment constraints, like if
1736 // the field is packed, the struct is packed, or the struct has a
1737 // a max-field-alignment constraint (#pragma pack). So calculate
1738 // the actual alignment of the field within the struct, and then
1739 // (as we're expected to) constrain that by the alignment of the type.
1740 if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
1741 const RecordDecl *Parent = Field->getParent();
1742 // We can only produce a sensible answer if the record is valid.
1743 if (!Parent->isInvalidDecl()) {
1744 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
1745
1746 // Start with the record's overall alignment.
1747 unsigned FieldAlign = toBits(Layout.getAlignment());
1748
1749 // Use the GCD of that and the offset within the record.
1750 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1751 if (Offset > 0) {
1752 // Alignment is always a power of 2, so the GCD will be a power of 2,
1753 // which means we get to do this crazy thing instead of Euclid's.
1754 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1755 if (LowBitOfOffset < FieldAlign)
1756 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1757 }
1758
1759 Align = std::min(Align, FieldAlign);
1760 }
1761 }
1762 }
1763
1764 // Some targets have hard limitation on the maximum requestable alignment in
1765 // aligned attribute for static variables.
1766 const unsigned MaxAlignedAttr = getTargetInfo().getMaxAlignedAttribute();
1767 const auto *VD = dyn_cast<VarDecl>(D);
1768 if (MaxAlignedAttr && VD && VD->getStorageClass() == SC_Static)
1769 Align = std::min(Align, MaxAlignedAttr);
1770
1771 return toCharUnitsFromBits(Align);
1772}
1773
1775 return toCharUnitsFromBits(Target->getExnObjectAlignment());
1776}
1777
1778// getTypeInfoDataSizeInChars - Return the size of a type, in
1779// chars. If the type is a record, its data size is returned. This is
1780// the size of the memcpy that's performed when assigning this type
1781// using a trivial copy/move assignment operator.
1784
1785 // In C++, objects can sometimes be allocated into the tail padding
1786 // of a base-class subobject. We decide whether that's possible
1787 // during class layout, so here we can just trust the layout results.
1788 if (getLangOpts().CPlusPlus) {
1789 if (const auto *RT = T->getAs<RecordType>();
1790 RT && !RT->getDecl()->isInvalidDecl()) {
1791 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1792 Info.Width = layout.getDataSize();
1793 }
1794 }
1795
1796 return Info;
1797}
1798
1799/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1800/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1803 const ConstantArrayType *CAT) {
1804 TypeInfoChars EltInfo = Context.getTypeInfoInChars(CAT->getElementType());
1805 uint64_t Size = CAT->getZExtSize();
1806 assert((Size == 0 || static_cast<uint64_t>(EltInfo.Width.getQuantity()) <=
1807 (uint64_t)(-1)/Size) &&
1808 "Overflow in array type char size evaluation");
1809 uint64_t Width = EltInfo.Width.getQuantity() * Size;
1810 unsigned Align = EltInfo.Align.getQuantity();
1811 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1813 Width = llvm::alignTo(Width, Align);
1816 EltInfo.AlignRequirement);
1817}
1818
1820 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
1821 return getConstantArrayInfoInChars(*this, CAT);
1822 TypeInfo Info = getTypeInfo(T);
1825}
1826
1828 return getTypeInfoInChars(T.getTypePtr());
1829}
1830
1832 // HLSL doesn't promote all small integer types to int, it
1833 // just uses the rank-based promotion rules for all types.
1834 if (getLangOpts().HLSL)
1835 return false;
1836
1837 if (const auto *BT = T->getAs<BuiltinType>())
1838 switch (BT->getKind()) {
1839 case BuiltinType::Bool:
1840 case BuiltinType::Char_S:
1841 case BuiltinType::Char_U:
1842 case BuiltinType::SChar:
1843 case BuiltinType::UChar:
1844 case BuiltinType::Short:
1845 case BuiltinType::UShort:
1846 case BuiltinType::WChar_S:
1847 case BuiltinType::WChar_U:
1848 case BuiltinType::Char8:
1849 case BuiltinType::Char16:
1850 case BuiltinType::Char32:
1851 return true;
1852 default:
1853 return false;
1854 }
1855
1856 // Enumerated types are promotable to their compatible integer types
1857 // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
1858 if (const auto *ET = T->getAs<EnumType>()) {
1859 if (T->isDependentType() || ET->getDecl()->getPromotionType().isNull() ||
1860 ET->getDecl()->isScoped())
1861 return false;
1862
1863 return true;
1864 }
1865
1866 return false;
1867}
1868
1871}
1872
1874 return isAlignmentRequired(T.getTypePtr());
1875}
1876
1878 bool NeedsPreferredAlignment) const {
1879 // An alignment on a typedef overrides anything else.
1880 if (const auto *TT = T->getAs<TypedefType>())
1881 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1882 return Align;
1883
1884 // If we have an (array of) complete type, we're done.
1886 if (!T->isIncompleteType())
1887 return NeedsPreferredAlignment ? getPreferredTypeAlign(T) : getTypeAlign(T);
1888
1889 // If we had an array type, its element type might be a typedef
1890 // type with an alignment attribute.
1891 if (const auto *TT = T->getAs<TypedefType>())
1892 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1893 return Align;
1894
1895 // Otherwise, see if the declaration of the type had an attribute.
1896 if (const auto *TT = T->getAs<TagType>())
1897 return TT->getDecl()->getMaxAlignment();
1898
1899 return 0;
1900}
1901
1903 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1904 if (I != MemoizedTypeInfo.end())
1905 return I->second;
1906
1907 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1908 TypeInfo TI = getTypeInfoImpl(T);
1909 MemoizedTypeInfo[T] = TI;
1910 return TI;
1911}
1912
1913/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1914/// method does not work on incomplete types.
1915///
1916/// FIXME: Pointers into different addr spaces could have different sizes and
1917/// alignment requirements: getPointerInfo should take an AddrSpace, this
1918/// should take a QualType, &c.
1919TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1920 uint64_t Width = 0;
1921 unsigned Align = 8;
1924 switch (T->getTypeClass()) {
1925#define TYPE(Class, Base)
1926#define ABSTRACT_TYPE(Class, Base)
1927#define NON_CANONICAL_TYPE(Class, Base)
1928#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1929#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1930 case Type::Class: \
1931 assert(!T->isDependentType() && "should not see dependent types here"); \
1932 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
1933#include "clang/AST/TypeNodes.inc"
1934 llvm_unreachable("Should not see dependent types");
1935
1936 case Type::FunctionNoProto:
1937 case Type::FunctionProto:
1938 // GCC extension: alignof(function) = 32 bits
1939 Width = 0;
1940 Align = 32;
1941 break;
1942
1943 case Type::IncompleteArray:
1944 case Type::VariableArray:
1945 case Type::ConstantArray:
1946 case Type::ArrayParameter: {
1947 // Model non-constant sized arrays as size zero, but track the alignment.
1948 uint64_t Size = 0;
1949 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
1950 Size = CAT->getZExtSize();
1951
1952 TypeInfo EltInfo = getTypeInfo(cast<ArrayType>(T)->getElementType());
1953 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
1954 "Overflow in array type bit size evaluation");
1955 Width = EltInfo.Width * Size;
1956 Align = EltInfo.Align;
1957 AlignRequirement = EltInfo.AlignRequirement;
1958 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1959 getTargetInfo().getPointerWidth(LangAS::Default) == 64)
1960 Width = llvm::alignTo(Width, Align);
1961 break;
1962 }
1963
1964 case Type::ExtVector:
1965 case Type::Vector: {
1966 const auto *VT = cast<VectorType>(T);
1967 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1968 Width = VT->isExtVectorBoolType() ? VT->getNumElements()
1969 : EltInfo.Width * VT->getNumElements();
1970 // Enforce at least byte size and alignment.
1971 Width = std::max<unsigned>(8, Width);
1972 Align = std::max<unsigned>(8, Width);
1973
1974 // If the alignment is not a power of 2, round up to the next power of 2.
1975 // This happens for non-power-of-2 length vectors.
1976 if (Align & (Align-1)) {
1977 Align = llvm::bit_ceil(Align);
1978 Width = llvm::alignTo(Width, Align);
1979 }
1980 // Adjust the alignment based on the target max.
1981 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1982 if (TargetVectorAlign && TargetVectorAlign < Align)
1983 Align = TargetVectorAlign;
1984 if (VT->getVectorKind() == VectorKind::SveFixedLengthData)
1985 // Adjust the alignment for fixed-length SVE vectors. This is important
1986 // for non-power-of-2 vector lengths.
1987 Align = 128;
1988 else if (VT->getVectorKind() == VectorKind::SveFixedLengthPredicate)
1989 // Adjust the alignment for fixed-length SVE predicates.
1990 Align = 16;
1991 else if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
1992 VT->getVectorKind() == VectorKind::RVVFixedLengthMask ||
1993 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_1 ||
1994 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_2 ||
1995 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_4)
1996 // Adjust the alignment for fixed-length RVV vectors.
1997 Align = std::min<unsigned>(64, Width);
1998 break;
1999 }
2000
2001 case Type::ConstantMatrix: {
2002 const auto *MT = cast<ConstantMatrixType>(T);
2003 TypeInfo ElementInfo = getTypeInfo(MT->getElementType());
2004 // The internal layout of a matrix value is implementation defined.
2005 // Initially be ABI compatible with arrays with respect to alignment and
2006 // size.
2007 Width = ElementInfo.Width * MT->getNumRows() * MT->getNumColumns();
2008 Align = ElementInfo.Align;
2009 break;
2010 }
2011
2012 case Type::Builtin:
2013 switch (cast<BuiltinType>(T)->getKind()) {
2014 default: llvm_unreachable("Unknown builtin type!");
2015 case BuiltinType::Void:
2016 // GCC extension: alignof(void) = 8 bits.
2017 Width = 0;
2018 Align = 8;
2019 break;
2020 case BuiltinType::Bool:
2021 Width = Target->getBoolWidth();
2022 Align = Target->getBoolAlign();
2023 break;
2024 case BuiltinType::Char_S:
2025 case BuiltinType::Char_U:
2026 case BuiltinType::UChar:
2027 case BuiltinType::SChar:
2028 case BuiltinType::Char8:
2029 Width = Target->getCharWidth();
2030 Align = Target->getCharAlign();
2031 break;
2032 case BuiltinType::WChar_S:
2033 case BuiltinType::WChar_U:
2034 Width = Target->getWCharWidth();
2035 Align = Target->getWCharAlign();
2036 break;
2037 case BuiltinType::Char16:
2038 Width = Target->getChar16Width();
2039 Align = Target->getChar16Align();
2040 break;
2041 case BuiltinType::Char32:
2042 Width = Target->getChar32Width();
2043 Align = Target->getChar32Align();
2044 break;
2045 case BuiltinType::UShort:
2046 case BuiltinType::Short:
2047 Width = Target->getShortWidth();
2048 Align = Target->getShortAlign();
2049 break;
2050 case BuiltinType::UInt:
2051 case BuiltinType::Int:
2052 Width = Target->getIntWidth();
2053 Align = Target->getIntAlign();
2054 break;
2055 case BuiltinType::ULong:
2056 case BuiltinType::Long:
2057 Width = Target->getLongWidth();
2058 Align = Target->getLongAlign();
2059 break;
2060 case BuiltinType::ULongLong:
2061 case BuiltinType::LongLong:
2062 Width = Target->getLongLongWidth();
2063 Align = Target->getLongLongAlign();
2064 break;
2065 case BuiltinType::Int128:
2066 case BuiltinType::UInt128:
2067 Width = 128;
2068 Align = Target->getInt128Align();
2069 break;
2070 case BuiltinType::ShortAccum:
2071 case BuiltinType::UShortAccum:
2072 case BuiltinType::SatShortAccum:
2073 case BuiltinType::SatUShortAccum:
2074 Width = Target->getShortAccumWidth();
2075 Align = Target->getShortAccumAlign();
2076 break;
2077 case BuiltinType::Accum:
2078 case BuiltinType::UAccum:
2079 case BuiltinType::SatAccum:
2080 case BuiltinType::SatUAccum:
2081 Width = Target->getAccumWidth();
2082 Align = Target->getAccumAlign();
2083 break;
2084 case BuiltinType::LongAccum:
2085 case BuiltinType::ULongAccum:
2086 case BuiltinType::SatLongAccum:
2087 case BuiltinType::SatULongAccum:
2088 Width = Target->getLongAccumWidth();
2089 Align = Target->getLongAccumAlign();
2090 break;
2091 case BuiltinType::ShortFract:
2092 case BuiltinType::UShortFract:
2093 case BuiltinType::SatShortFract:
2094 case BuiltinType::SatUShortFract:
2095 Width = Target->getShortFractWidth();
2096 Align = Target->getShortFractAlign();
2097 break;
2098 case BuiltinType::Fract:
2099 case BuiltinType::UFract:
2100 case BuiltinType::SatFract:
2101 case BuiltinType::SatUFract:
2102 Width = Target->getFractWidth();
2103 Align = Target->getFractAlign();
2104 break;
2105 case BuiltinType::LongFract:
2106 case BuiltinType::ULongFract:
2107 case BuiltinType::SatLongFract:
2108 case BuiltinType::SatULongFract:
2109 Width = Target->getLongFractWidth();
2110 Align = Target->getLongFractAlign();
2111 break;
2112 case BuiltinType::BFloat16:
2113 if (Target->hasBFloat16Type()) {
2114 Width = Target->getBFloat16Width();
2115 Align = Target->getBFloat16Align();
2116 } else if ((getLangOpts().SYCLIsDevice ||
2117 (getLangOpts().OpenMP &&
2118 getLangOpts().OpenMPIsTargetDevice)) &&
2119 AuxTarget->hasBFloat16Type()) {
2120 Width = AuxTarget->getBFloat16Width();
2121 Align = AuxTarget->getBFloat16Align();
2122 }
2123 break;
2124 case BuiltinType::Float16:
2125 case BuiltinType::Half:
2126 if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
2127 !getLangOpts().OpenMPIsTargetDevice) {
2128 Width = Target->getHalfWidth();
2129 Align = Target->getHalfAlign();
2130 } else {
2131 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2132 "Expected OpenMP device compilation.");
2133 Width = AuxTarget->getHalfWidth();
2134 Align = AuxTarget->getHalfAlign();
2135 }
2136 break;
2137 case BuiltinType::Float:
2138 Width = Target->getFloatWidth();
2139 Align = Target->getFloatAlign();
2140 break;
2141 case BuiltinType::Double:
2142 Width = Target->getDoubleWidth();
2143 Align = Target->getDoubleAlign();
2144 break;
2145 case BuiltinType::Ibm128:
2146 Width = Target->getIbm128Width();
2147 Align = Target->getIbm128Align();
2148 break;
2149 case BuiltinType::LongDouble:
2150 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2151 (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() ||
2152 Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) {
2153 Width = AuxTarget->getLongDoubleWidth();
2154 Align = AuxTarget->getLongDoubleAlign();
2155 } else {
2156 Width = Target->getLongDoubleWidth();
2157 Align = Target->getLongDoubleAlign();
2158 }
2159 break;
2160 case BuiltinType::Float128:
2161 if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
2162 !getLangOpts().OpenMPIsTargetDevice) {
2163 Width = Target->getFloat128Width();
2164 Align = Target->getFloat128Align();
2165 } else {
2166 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2167 "Expected OpenMP device compilation.");
2168 Width = AuxTarget->getFloat128Width();
2169 Align = AuxTarget->getFloat128Align();
2170 }
2171 break;
2172 case BuiltinType::NullPtr:
2173 // C++ 3.9.1p11: sizeof(nullptr_t) == sizeof(void*)
2174 Width = Target->getPointerWidth(LangAS::Default);
2175 Align = Target->getPointerAlign(LangAS::Default);
2176 break;
2177 case BuiltinType::ObjCId:
2178 case BuiltinType::ObjCClass:
2179 case BuiltinType::ObjCSel:
2180 Width = Target->getPointerWidth(LangAS::Default);
2181 Align = Target->getPointerAlign(LangAS::Default);
2182 break;
2183 case BuiltinType::OCLSampler:
2184 case BuiltinType::OCLEvent:
2185 case BuiltinType::OCLClkEvent:
2186 case BuiltinType::OCLQueue:
2187 case BuiltinType::OCLReserveID:
2188#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2189 case BuiltinType::Id:
2190#include "clang/Basic/OpenCLImageTypes.def"
2191#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2192 case BuiltinType::Id:
2193#include "clang/Basic/OpenCLExtensionTypes.def"
2194 AS = Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
2195 Width = Target->getPointerWidth(AS);
2196 Align = Target->getPointerAlign(AS);
2197 break;
2198 // The SVE types are effectively target-specific. The length of an
2199 // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple
2200 // of 128 bits. There is one predicate bit for each vector byte, so the
2201 // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits.
2202 //
2203 // Because the length is only known at runtime, we use a dummy value
2204 // of 0 for the static length. The alignment values are those defined
2205 // by the Procedure Call Standard for the Arm Architecture.
2206#define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits, \
2207 IsSigned, IsFP, IsBF) \
2208 case BuiltinType::Id: \
2209 Width = 0; \
2210 Align = 128; \
2211 break;
2212#define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls) \
2213 case BuiltinType::Id: \
2214 Width = 0; \
2215 Align = 16; \
2216 break;
2217#define SVE_OPAQUE_TYPE(Name, MangledName, Id, SingletonId) \
2218 case BuiltinType::Id: \
2219 Width = 0; \
2220 Align = 16; \
2221 break;
2222#include "clang/Basic/AArch64SVEACLETypes.def"
2223#define PPC_VECTOR_TYPE(Name, Id, Size) \
2224 case BuiltinType::Id: \
2225 Width = Size; \
2226 Align = Size; \
2227 break;
2228#include "clang/Basic/PPCTypes.def"
2229#define RVV_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, NF, IsSigned, \
2230 IsFP, IsBF) \
2231 case BuiltinType::Id: \
2232 Width = 0; \
2233 Align = ElBits; \
2234 break;
2235#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, ElKind) \
2236 case BuiltinType::Id: \
2237 Width = 0; \
2238 Align = 8; \
2239 break;
2240#include "clang/Basic/RISCVVTypes.def"
2241#define WASM_TYPE(Name, Id, SingletonId) \
2242 case BuiltinType::Id: \
2243 Width = 0; \
2244 Align = 8; \
2245 break;
2246#include "clang/Basic/WebAssemblyReferenceTypes.def"
2247#define AMDGPU_OPAQUE_PTR_TYPE(NAME, MANGLEDNAME, AS, WIDTH, ALIGN, ID, \
2248 SINGLETONID) \
2249 case BuiltinType::ID: \
2250 Width = WIDTH; \
2251 Align = ALIGN; \
2252 break;
2253#include "clang/Basic/AMDGPUTypes.def"
2254#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
2255#include "clang/Basic/HLSLIntangibleTypes.def"
2256 Width = 0;
2257 Align = 8;
2258 break;
2259 }
2260 break;
2261 case Type::ObjCObjectPointer:
2262 Width = Target->getPointerWidth(LangAS::Default);
2263 Align = Target->getPointerAlign(LangAS::Default);
2264 break;
2265 case Type::BlockPointer:
2266 AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
2267 Width = Target->getPointerWidth(AS);
2268 Align = Target->getPointerAlign(AS);
2269 break;
2270 case Type::LValueReference:
2271 case Type::RValueReference:
2272 // alignof and sizeof should never enter this code path here, so we go
2273 // the pointer route.
2274 AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
2275 Width = Target->getPointerWidth(AS);
2276 Align = Target->getPointerAlign(AS);
2277 break;
2278 case Type::Pointer:
2279 AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
2280 Width = Target->getPointerWidth(AS);
2281 Align = Target->getPointerAlign(AS);
2282 break;
2283 case Type::MemberPointer: {
2284 const auto *MPT = cast<MemberPointerType>(T);
2285 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
2286 Width = MPI.Width;
2287 Align = MPI.Align;
2288 break;
2289 }
2290 case Type::Complex: {
2291 // Complex types have the same alignment as their elements, but twice the
2292 // size.
2293 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
2294 Width = EltInfo.Width * 2;
2295 Align = EltInfo.Align;
2296 break;
2297 }
2298 case Type::ObjCObject:
2299 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
2300 case Type::Adjusted:
2301 case Type::Decayed:
2302 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
2303 case Type::ObjCInterface: {
2304 const auto *ObjCI = cast<ObjCInterfaceType>(T);
2305 if (ObjCI->getDecl()->isInvalidDecl()) {
2306 Width = 8;
2307 Align = 8;
2308 break;
2309 }
2310 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2311 Width = toBits(Layout.getSize());
2312 Align = toBits(Layout.getAlignment());
2313 break;
2314 }
2315 case Type::BitInt: {
2316 const auto *EIT = cast<BitIntType>(T);
2317 Align = Target->getBitIntAlign(EIT->getNumBits());
2318 Width = Target->getBitIntWidth(EIT->getNumBits());
2319 break;
2320 }
2321 case Type::Record:
2322 case Type::Enum: {
2323 const auto *TT = cast<TagType>(T);
2324
2325 if (TT->getDecl()->isInvalidDecl()) {
2326 Width = 8;
2327 Align = 8;
2328 break;
2329 }
2330
2331 if (const auto *ET = dyn_cast<EnumType>(TT)) {
2332 const EnumDecl *ED = ET->getDecl();
2333 TypeInfo Info =
2335 if (unsigned AttrAlign = ED->getMaxAlignment()) {
2336 Info.Align = AttrAlign;
2338 }
2339 return Info;
2340 }
2341
2342 const auto *RT = cast<RecordType>(TT);
2343 const RecordDecl *RD = RT->getDecl();
2344 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2345 Width = toBits(Layout.getSize());
2346 Align = toBits(Layout.getAlignment());
2347 AlignRequirement = RD->hasAttr<AlignedAttr>()
2350 break;
2351 }
2352
2353 case Type::SubstTemplateTypeParm:
2354 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
2355 getReplacementType().getTypePtr());
2356
2357 case Type::Auto:
2358 case Type::DeducedTemplateSpecialization: {
2359 const auto *A = cast<DeducedType>(T);
2360 assert(!A->getDeducedType().isNull() &&
2361 "cannot request the size of an undeduced or dependent auto type");
2362 return getTypeInfo(A->getDeducedType().getTypePtr());
2363 }
2364
2365 case Type::Paren:
2366 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
2367
2368 case Type::MacroQualified:
2369 return getTypeInfo(
2370 cast<MacroQualifiedType>(T)->getUnderlyingType().getTypePtr());
2371
2372 case Type::ObjCTypeParam:
2373 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
2374
2375 case Type::Using:
2376 return getTypeInfo(cast<UsingType>(T)->desugar().getTypePtr());
2377
2378 case Type::Typedef: {
2379 const auto *TT = cast<TypedefType>(T);
2380 TypeInfo Info = getTypeInfo(TT->desugar().getTypePtr());
2381 // If the typedef has an aligned attribute on it, it overrides any computed
2382 // alignment we have. This violates the GCC documentation (which says that
2383 // attribute(aligned) can only round up) but matches its implementation.
2384 if (unsigned AttrAlign = TT->getDecl()->getMaxAlignment()) {
2385 Align = AttrAlign;
2386 AlignRequirement = AlignRequirementKind::RequiredByTypedef;
2387 } else {
2388 Align = Info.Align;
2389 AlignRequirement = Info.AlignRequirement;
2390 }
2391 Width = Info.Width;
2392 break;
2393 }
2394
2395 case Type::Elaborated:
2396 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
2397
2398 case Type::Attributed:
2399 return getTypeInfo(
2400 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
2401
2402 case Type::CountAttributed:
2403 return getTypeInfo(cast<CountAttributedType>(T)->desugar().getTypePtr());
2404
2405 case Type::BTFTagAttributed:
2406 return getTypeInfo(
2407 cast<BTFTagAttributedType>(T)->getWrappedType().getTypePtr());
2408
2409 case Type::Atomic: {
2410 // Start with the base type information.
2411 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
2412 Width = Info.Width;
2413 Align = Info.Align;
2414
2415 if (!Width) {
2416 // An otherwise zero-sized type should still generate an
2417 // atomic operation.
2418 Width = Target->getCharWidth();
2419 assert(Align);
2420 } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2421 // If the size of the type doesn't exceed the platform's max
2422 // atomic promotion width, make the size and alignment more
2423 // favorable to atomic operations:
2424
2425 // Round the size up to a power of 2.
2426 Width = llvm::bit_ceil(Width);
2427
2428 // Set the alignment equal to the size.
2429 Align = static_cast<unsigned>(Width);
2430 }
2431 }
2432 break;
2433
2434 case Type::Pipe:
2435 Width = Target->getPointerWidth(LangAS::opencl_global);
2436 Align = Target->getPointerAlign(LangAS::opencl_global);
2437 break;
2438 }
2439
2440 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
2441 return TypeInfo(Width, Align, AlignRequirement);
2442}
2443
2445 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
2446 if (I != MemoizedUnadjustedAlign.end())
2447 return I->second;
2448
2449 unsigned UnadjustedAlign;
2450 if (const auto *RT = T->getAs<RecordType>()) {
2451 const RecordDecl *RD = RT->getDecl();
2452 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2453 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2454 } else if (const auto *ObjCI = T->getAs<ObjCInterfaceType>()) {
2455 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2456 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2457 } else {
2458 UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType());
2459 }
2460
2461 MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2462 return UnadjustedAlign;
2463}
2464
2466 unsigned SimdAlign = llvm::OpenMPIRBuilder::getOpenMPDefaultSimdAlign(
2467 getTargetInfo().getTriple(), Target->getTargetOpts().FeatureMap);
2468 return SimdAlign;
2469}
2470
2471/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2473 return CharUnits::fromQuantity(BitSize / getCharWidth());
2474}
2475
2476/// toBits - Convert a size in characters to a size in characters.
2477int64_t ASTContext::toBits(CharUnits CharSize) const {
2478 return CharSize.getQuantity() * getCharWidth();
2479}
2480
2481/// getTypeSizeInChars - Return the size of the specified type, in characters.
2482/// This method does not work on incomplete types.
2484 return getTypeInfoInChars(T).Width;
2485}
2487 return getTypeInfoInChars(T).Width;
2488}
2489
2490/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
2491/// characters. This method does not work on incomplete types.
2494}
2497}
2498
2499/// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2500/// type, in characters, before alignment adjustments. This method does
2501/// not work on incomplete types.
2504}
2507}
2508
2509/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2510/// type for the current target in bits. This can be different than the ABI
2511/// alignment in cases where it is beneficial for performance or backwards
2512/// compatibility preserving to overalign a data type. (Note: despite the name,
2513/// the preferred alignment is ABI-impacting, and not an optimization.)
2515 TypeInfo TI = getTypeInfo(T);
2516 unsigned ABIAlign = TI.Align;
2517
2519
2520 // The preferred alignment of member pointers is that of a pointer.
2521 if (T->isMemberPointerType())
2522 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2523
2524 if (!Target->allowsLargerPreferedTypeAlignment())
2525 return ABIAlign;
2526
2527 if (const auto *RT = T->getAs<RecordType>()) {
2528 const RecordDecl *RD = RT->getDecl();
2529
2530 // When used as part of a typedef, or together with a 'packed' attribute,
2531 // the 'aligned' attribute can be used to decrease alignment. Note that the
2532 // 'packed' case is already taken into consideration when computing the
2533 // alignment, we only need to handle the typedef case here.
2535 RD->isInvalidDecl())
2536 return ABIAlign;
2537
2538 unsigned PreferredAlign = static_cast<unsigned>(
2539 toBits(getASTRecordLayout(RD).PreferredAlignment));
2540 assert(PreferredAlign >= ABIAlign &&
2541 "PreferredAlign should be at least as large as ABIAlign.");
2542 return PreferredAlign;
2543 }
2544
2545 // Double (and, for targets supporting AIX `power` alignment, long double) and
2546 // long long should be naturally aligned (despite requiring less alignment) if
2547 // possible.
2548 if (const auto *CT = T->getAs<ComplexType>())
2549 T = CT->getElementType().getTypePtr();
2550 if (const auto *ET = T->getAs<EnumType>())
2551 T = ET->getDecl()->getIntegerType().getTypePtr();
2552 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
2553 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2554 T->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2555 (T->isSpecificBuiltinType(BuiltinType::LongDouble) &&
2556 Target->defaultsToAIXPowerAlignment()))
2557 // Don't increase the alignment if an alignment attribute was specified on a
2558 // typedef declaration.
2559 if (!TI.isAlignRequired())
2560 return std::max(ABIAlign, (unsigned)getTypeSize(T));
2561
2562 return ABIAlign;
2563}
2564
2565/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2566/// for __attribute__((aligned)) on this target, to be used if no alignment
2567/// value is specified.
2570}
2571
2572/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2573/// to a global variable of the specified type.
2575 uint64_t TypeSize = getTypeSize(T.getTypePtr());
2576 return std::max(getPreferredTypeAlign(T),
2577 getMinGlobalAlignOfVar(TypeSize, VD));
2578}
2579
2580/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2581/// should be given to a global variable of the specified type.
2583 const VarDecl *VD) const {
2585}
2586
2588 const VarDecl *VD) const {
2589 // Make the default handling as that of a non-weak definition in the
2590 // current translation unit.
2591 bool HasNonWeakDef = !VD || (VD->hasDefinition() && !VD->isWeak());
2592 return getTargetInfo().getMinGlobalAlign(Size, HasNonWeakDef);
2593}
2594
2596 CharUnits Offset = CharUnits::Zero();
2597 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2598 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2599 Offset += Layout->getBaseClassOffset(Base);
2600 Layout = &getASTRecordLayout(Base);
2601 }
2602 return Offset;
2603}
2604
2606 const ValueDecl *MPD = MP.getMemberPointerDecl();
2609 bool DerivedMember = MP.isMemberPointerToDerivedMember();
2610 const CXXRecordDecl *RD = cast<CXXRecordDecl>(MPD->getDeclContext());
2611 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
2612 const CXXRecordDecl *Base = RD;
2613 const CXXRecordDecl *Derived = Path[I];
2614 if (DerivedMember)
2615 std::swap(Base, Derived);
2617 RD = Path[I];
2618 }
2619 if (DerivedMember)
2621 return ThisAdjustment;
2622}
2623
2624/// DeepCollectObjCIvars -
2625/// This routine first collects all declared, but not synthesized, ivars in
2626/// super class and then collects all ivars, including those synthesized for
2627/// current class. This routine is used for implementation of current class
2628/// when all ivars, declared and synthesized are known.
2630 bool leafClass,
2632 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2633 DeepCollectObjCIvars(SuperClass, false, Ivars);
2634 if (!leafClass) {
2635 llvm::append_range(Ivars, OI->ivars());
2636 } else {
2637 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
2638 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
2639 Iv= Iv->getNextIvar())
2640 Ivars.push_back(Iv);
2641 }
2642}
2643
2644/// CollectInheritedProtocols - Collect all protocols in current class and
2645/// those inherited by it.
2648 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2649 // We can use protocol_iterator here instead of
2650 // all_referenced_protocol_iterator since we are walking all categories.
2651 for (auto *Proto : OI->all_referenced_protocols()) {
2652 CollectInheritedProtocols(Proto, Protocols);
2653 }
2654
2655 // Categories of this Interface.
2656 for (const auto *Cat : OI->visible_categories())
2657 CollectInheritedProtocols(Cat, Protocols);
2658
2659 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2660 while (SD) {
2661 CollectInheritedProtocols(SD, Protocols);
2662 SD = SD->getSuperClass();
2663 }
2664 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
2665 for (auto *Proto : OC->protocols()) {
2666 CollectInheritedProtocols(Proto, Protocols);
2667 }
2668 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
2669 // Insert the protocol.
2670 if (!Protocols.insert(
2671 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2672 return;
2673
2674 for (auto *Proto : OP->protocols())
2675 CollectInheritedProtocols(Proto, Protocols);
2676 }
2677}
2678
2680 const RecordDecl *RD,
2681 bool CheckIfTriviallyCopyable) {
2682 assert(RD->isUnion() && "Must be union type");
2683 CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl());
2684
2685 for (const auto *Field : RD->fields()) {
2686 if (!Context.hasUniqueObjectRepresentations(Field->getType(),
2687 CheckIfTriviallyCopyable))
2688 return false;
2689 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2690 if (FieldSize != UnionSize)
2691 return false;
2692 }
2693 return !RD->field_empty();
2694}
2695
2696static int64_t getSubobjectOffset(const FieldDecl *Field,
2697 const ASTContext &Context,
2698 const clang::ASTRecordLayout & /*Layout*/) {
2699 return Context.getFieldOffset(Field);
2700}
2701
2702static int64_t getSubobjectOffset(const CXXRecordDecl *RD,
2703 const ASTContext &Context,
2704 const clang::ASTRecordLayout &Layout) {
2705 return Context.toBits(Layout.getBaseClassOffset(RD));
2706}
2707
2708static std::optional<int64_t>
2710 const RecordDecl *RD,
2711 bool CheckIfTriviallyCopyable);
2712
2713static std::optional<int64_t>
2714getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context,
2715 bool CheckIfTriviallyCopyable) {
2716 if (Field->getType()->isRecordType()) {
2717 const RecordDecl *RD = Field->getType()->getAsRecordDecl();
2718 if (!RD->isUnion())
2719 return structHasUniqueObjectRepresentations(Context, RD,
2720 CheckIfTriviallyCopyable);
2721 }
2722
2723 // A _BitInt type may not be unique if it has padding bits
2724 // but if it is a bitfield the padding bits are not used.
2725 bool IsBitIntType = Field->getType()->isBitIntType();
2726 if (!Field->getType()->isReferenceType() && !IsBitIntType &&
2727 !Context.hasUniqueObjectRepresentations(Field->getType(),
2728 CheckIfTriviallyCopyable))
2729 return std::nullopt;
2730
2731 int64_t FieldSizeInBits =
2732 Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2733 if (Field->isBitField()) {
2734 // If we have explicit padding bits, they don't contribute bits
2735 // to the actual object representation, so return 0.
2736 if (Field->isUnnamedBitField())
2737 return 0;
2738
2739 int64_t BitfieldSize = Field->getBitWidthValue(Context);
2740 if (IsBitIntType) {
2741 if ((unsigned)BitfieldSize >
2742 cast<BitIntType>(Field->getType())->getNumBits())
2743 return std::nullopt;
2744 } else if (BitfieldSize > FieldSizeInBits) {
2745 return std::nullopt;
2746 }
2747 FieldSizeInBits = BitfieldSize;
2748 } else if (IsBitIntType && !Context.hasUniqueObjectRepresentations(
2749 Field->getType(), CheckIfTriviallyCopyable)) {
2750 return std::nullopt;
2751 }
2752 return FieldSizeInBits;
2753}
2754
2755static std::optional<int64_t>
2757 bool CheckIfTriviallyCopyable) {
2758 return structHasUniqueObjectRepresentations(Context, RD,
2759 CheckIfTriviallyCopyable);
2760}
2761
2762template <typename RangeT>
2764 const RangeT &Subobjects, int64_t CurOffsetInBits,
2765 const ASTContext &Context, const clang::ASTRecordLayout &Layout,
2766 bool CheckIfTriviallyCopyable) {
2767 for (const auto *Subobject : Subobjects) {
2768 std::optional<int64_t> SizeInBits =
2769 getSubobjectSizeInBits(Subobject, Context, CheckIfTriviallyCopyable);
2770 if (!SizeInBits)
2771 return std::nullopt;
2772 if (*SizeInBits != 0) {
2773 int64_t Offset = getSubobjectOffset(Subobject, Context, Layout);
2774 if (Offset != CurOffsetInBits)
2775 return std::nullopt;
2776 CurOffsetInBits += *SizeInBits;
2777 }
2778 }
2779 return CurOffsetInBits;
2780}
2781
2782static std::optional<int64_t>
2784 const RecordDecl *RD,
2785 bool CheckIfTriviallyCopyable) {
2786 assert(!RD->isUnion() && "Must be struct/class type");
2787 const auto &Layout = Context.getASTRecordLayout(RD);
2788
2789 int64_t CurOffsetInBits = 0;
2790 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
2791 if (ClassDecl->isDynamicClass())
2792 return std::nullopt;
2793
2795 for (const auto &Base : ClassDecl->bases()) {
2796 // Empty types can be inherited from, and non-empty types can potentially
2797 // have tail padding, so just make sure there isn't an error.
2798 Bases.emplace_back(Base.getType()->getAsCXXRecordDecl());
2799 }
2800
2801 llvm::sort(Bases, [&](const CXXRecordDecl *L, const CXXRecordDecl *R) {
2802 return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R);
2803 });
2804
2805 std::optional<int64_t> OffsetAfterBases =
2807 Bases, CurOffsetInBits, Context, Layout, CheckIfTriviallyCopyable);
2808 if (!OffsetAfterBases)
2809 return std::nullopt;
2810 CurOffsetInBits = *OffsetAfterBases;
2811 }
2812
2813 std::optional<int64_t> OffsetAfterFields =
2815 RD->fields(), CurOffsetInBits, Context, Layout,
2816 CheckIfTriviallyCopyable);
2817 if (!OffsetAfterFields)
2818 return std::nullopt;
2819 CurOffsetInBits = *OffsetAfterFields;
2820
2821 return CurOffsetInBits;
2822}
2823
2825 QualType Ty, bool CheckIfTriviallyCopyable) const {
2826 // C++17 [meta.unary.prop]:
2827 // The predicate condition for a template specialization
2828 // has_unique_object_representations<T> shall be satisfied if and only if:
2829 // (9.1) - T is trivially copyable, and
2830 // (9.2) - any two objects of type T with the same value have the same
2831 // object representation, where:
2832 // - two objects of array or non-union class type are considered to have
2833 // the same value if their respective sequences of direct subobjects
2834 // have the same values, and
2835 // - two objects of union type are considered to have the same value if
2836 // they have the same active member and the corresponding members have
2837 // the same value.
2838 // The set of scalar types for which this condition holds is
2839 // implementation-defined. [ Note: If a type has padding bits, the condition
2840 // does not hold; otherwise, the condition holds true for unsigned integral
2841 // types. -- end note ]
2842 assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
2843
2844 // Arrays are unique only if their element type is unique.
2845 if (Ty->isArrayType())
2847 CheckIfTriviallyCopyable);
2848
2849 assert((Ty->isVoidType() || !Ty->isIncompleteType()) &&
2850 "hasUniqueObjectRepresentations should not be called with an "
2851 "incomplete type");
2852
2853 // (9.1) - T is trivially copyable...
2854 if (CheckIfTriviallyCopyable && !Ty.isTriviallyCopyableType(*this))
2855 return false;
2856
2857 // All integrals and enums are unique.
2858 if (Ty->isIntegralOrEnumerationType()) {
2859 // Except _BitInt types that have padding bits.
2860 if (const auto *BIT = Ty->getAs<BitIntType>())
2861 return getTypeSize(BIT) == BIT->getNumBits();
2862
2863 return true;
2864 }
2865
2866 // All other pointers are unique.
2867 if (Ty->isPointerType())
2868 return true;
2869
2870 if (const auto *MPT = Ty->getAs<MemberPointerType>())
2871 return !ABI->getMemberPointerInfo(MPT).HasPadding;
2872
2873 if (Ty->isRecordType()) {
2874 const RecordDecl *Record = Ty->castAs<RecordType>()->getDecl();
2875
2876 if (Record->isInvalidDecl())
2877 return false;
2878
2879 if (Record->isUnion())
2881 CheckIfTriviallyCopyable);
2882
2883 std::optional<int64_t> StructSize = structHasUniqueObjectRepresentations(
2884 *this, Record, CheckIfTriviallyCopyable);
2885
2886 return StructSize && *StructSize == static_cast<int64_t>(getTypeSize(Ty));
2887 }
2888
2889 // FIXME: More cases to handle here (list by rsmith):
2890 // vectors (careful about, eg, vector of 3 foo)
2891 // _Complex int and friends
2892 // _Atomic T
2893 // Obj-C block pointers
2894 // Obj-C object pointers
2895 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
2896 // clk_event_t, queue_t, reserve_id_t)
2897 // There're also Obj-C class types and the Obj-C selector type, but I think it
2898 // makes sense for those to return false here.
2899
2900 return false;
2901}
2902
2904 unsigned count = 0;
2905 // Count ivars declared in class extension.
2906 for (const auto *Ext : OI->known_extensions())
2907 count += Ext->ivar_size();
2908
2909 // Count ivar defined in this class's implementation. This
2910 // includes synthesized ivars.
2911 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
2912 count += ImplDecl->ivar_size();
2913
2914 return count;
2915}
2916
2918 if (!E)
2919 return false;
2920
2921 // nullptr_t is always treated as null.
2922 if (E->getType()->isNullPtrType()) return true;
2923
2924 if (E->getType()->isAnyPointerType() &&
2927 return true;
2928
2929 // Unfortunately, __null has type 'int'.
2930 if (isa<GNUNullExpr>(E)) return true;
2931
2932 return false;
2933}
2934
2935/// Get the implementation of ObjCInterfaceDecl, or nullptr if none
2936/// exists.
2938 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2939 I = ObjCImpls.find(D);
2940 if (I != ObjCImpls.end())
2941 return cast<ObjCImplementationDecl>(I->second);
2942 return nullptr;
2943}
2944
2945/// Get the implementation of ObjCCategoryDecl, or nullptr if none
2946/// exists.
2948 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2949 I = ObjCImpls.find(D);
2950 if (I != ObjCImpls.end())
2951 return cast<ObjCCategoryImplDecl>(I->second);
2952 return nullptr;
2953}
2954
2955/// Set the implementation of ObjCInterfaceDecl.
2957 ObjCImplementationDecl *ImplD) {
2958 assert(IFaceD && ImplD && "Passed null params");
2959 ObjCImpls[IFaceD] = ImplD;
2960}
2961
2962/// Set the implementation of ObjCCategoryDecl.
2964 ObjCCategoryImplDecl *ImplD) {
2965 assert(CatD && ImplD && "Passed null params");
2966 ObjCImpls[CatD] = ImplD;
2967}
2968
2969const ObjCMethodDecl *
2971 return ObjCMethodRedecls.lookup(MD);
2972}
2973
2975 const ObjCMethodDecl *Redecl) {
2976 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2977 ObjCMethodRedecls[MD] = Redecl;
2978}
2979
2981 const NamedDecl *ND) const {
2982 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
2983 return ID;
2984 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
2985 return CD->getClassInterface();
2986 if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
2987 return IMD->getClassInterface();
2988
2989 return nullptr;
2990}
2991
2992/// Get the copy initialization expression of VarDecl, or nullptr if
2993/// none exists.
2995 assert(VD && "Passed null params");
2996 assert(VD->hasAttr<BlocksAttr>() &&
2997 "getBlockVarCopyInits - not __block var");
2998 auto I = BlockVarCopyInits.find(VD);
2999 if (I != BlockVarCopyInits.end())
3000 return I->second;
3001 return {nullptr, false};
3002}
3003
3004/// Set the copy initialization expression of a block var decl.
3006 bool CanThrow) {
3007 assert(VD && CopyExpr && "Passed null params");
3008 assert(VD->hasAttr<BlocksAttr>() &&
3009 "setBlockVarCopyInits - not __block var");
3010 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
3011}
3012
3014 unsigned DataSize) const {
3015 if (!DataSize)
3017 else
3018 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
3019 "incorrect data size provided to CreateTypeSourceInfo!");
3020
3021 auto *TInfo =
3022 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
3023 new (TInfo) TypeSourceInfo(T, DataSize);
3024 return TInfo;
3025}
3026
3028 SourceLocation L) const {
3030 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
3031 return DI;
3032}
3033
3034const ASTRecordLayout &
3036 return getObjCLayout(D, nullptr);
3037}
3038
3039const ASTRecordLayout &
3041 const ObjCImplementationDecl *D) const {
3042 return getObjCLayout(D->getClassInterface(), D);
3043}
3044
3047 bool &AnyNonCanonArgs) {
3048 SmallVector<TemplateArgument, 16> CanonArgs(Args);
3049 for (auto &Arg : CanonArgs) {
3050 TemplateArgument OrigArg = Arg;
3051 Arg = C.getCanonicalTemplateArgument(Arg);
3052 AnyNonCanonArgs |= !Arg.structurallyEquals(OrigArg);
3053 }
3054 return CanonArgs;
3055}
3056
3057//===----------------------------------------------------------------------===//
3058// Type creation/memoization methods
3059//===----------------------------------------------------------------------===//
3060
3062ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
3063 unsigned fastQuals = quals.getFastQualifiers();
3064 quals.removeFastQualifiers();
3065
3066 // Check if we've already instantiated this type.
3067 llvm::FoldingSetNodeID ID;
3068 ExtQuals::Profile(ID, baseType, quals);
3069 void *insertPos = nullptr;
3070 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
3071 assert(eq->getQualifiers() == quals);
3072 return QualType(eq, fastQuals);
3073 }
3074
3075 // If the base type is not canonical, make the appropriate canonical type.
3076 QualType canon;
3077 if (!baseType->isCanonicalUnqualified()) {
3078 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
3079 canonSplit.Quals.addConsistentQualifiers(quals);
3080 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
3081
3082 // Re-find the insert position.
3083 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
3084 }
3085
3086 auto *eq = new (*this, alignof(ExtQuals)) ExtQuals(baseType, canon, quals);
3087 ExtQualNodes.InsertNode(eq, insertPos);
3088 return QualType(eq, fastQuals);
3089}
3090
3092 LangAS AddressSpace) const {
3093 QualType CanT = getCanonicalType(T);
3094 if (CanT.getAddressSpace() == AddressSpace)
3095 return T;
3096
3097 // If we are composing extended qualifiers together, merge together
3098 // into one ExtQuals node.
3099 QualifierCollector Quals;
3100 const Type *TypeNode = Quals.strip(T);
3101
3102 // If this type already has an address space specified, it cannot get
3103 // another one.
3104 assert(!Quals.hasAddressSpace() &&
3105 "Type cannot be in multiple addr spaces!");
3106 Quals.addAddressSpace(AddressSpace);
3107
3108 return getExtQualType(TypeNode, Quals);
3109}
3110
3112 // If the type is not qualified with an address space, just return it
3113 // immediately.
3114 if (!T.hasAddressSpace())
3115 return T;
3116
3117 QualifierCollector Quals;
3118 const Type *TypeNode;
3119 // For arrays, strip the qualifier off the element type, then reconstruct the
3120 // array type
3121 if (T.getTypePtr()->isArrayType()) {
3122 T = getUnqualifiedArrayType(T, Quals);
3123 TypeNode = T.getTypePtr();
3124 } else {
3125 // If we are composing extended qualifiers together, merge together
3126 // into one ExtQuals node.
3127 while (T.hasAddressSpace()) {
3128 TypeNode = Quals.strip(T);
3129
3130 // If the type no longer has an address space after stripping qualifiers,
3131 // jump out.
3132 if (!QualType(TypeNode, 0).hasAddressSpace())
3133 break;
3134
3135 // There might be sugar in the way. Strip it and try again.
3136 T = T.getSingleStepDesugaredType(*this);
3137 }
3138 }
3139
3140 Quals.removeAddressSpace();
3141
3142 // Removal of the address space can mean there are no longer any
3143 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
3144 // or required.
3145 if (Quals.hasNonFastQualifiers())
3146 return getExtQualType(TypeNode, Quals);
3147 else
3148 return QualType(TypeNode, Quals.getFastQualifiers());
3149}
3150
3151uint16_t
3153 assert(RD->isPolymorphic() &&
3154 "Attempted to get vtable pointer discriminator on a monomorphic type");
3155 std::unique_ptr<MangleContext> MC(createMangleContext());
3156 SmallString<256> Str;
3157 llvm::raw_svector_ostream Out(Str);
3158 MC->mangleCXXVTable(RD, Out);
3159 return llvm::getPointerAuthStableSipHash(Str);
3160}
3161
3162/// Encode a function type for use in the discriminator of a function pointer
3163/// type. We can't use the itanium scheme for this since C has quite permissive
3164/// rules for type compatibility that we need to be compatible with.
3165///
3166/// Formally, this function associates every function pointer type T with an
3167/// encoded string E(T). Let the equivalence relation T1 ~ T2 be defined as
3168/// E(T1) == E(T2). E(T) is part of the ABI of values of type T. C type
3169/// compatibility requires equivalent treatment under the ABI, so
3170/// CCompatible(T1, T2) must imply E(T1) == E(T2), that is, CCompatible must be
3171/// a subset of ~. Crucially, however, it must be a proper subset because
3172/// CCompatible is not an equivalence relation: for example, int[] is compatible
3173/// with both int[1] and int[2], but the latter are not compatible with each
3174/// other. Therefore this encoding function must be careful to only distinguish
3175/// types if there is no third type with which they are both required to be
3176/// compatible.
3178 raw_ostream &OS, QualType QT) {
3179 // FIXME: Consider address space qualifiers.
3180 const Type *T = QT.getCanonicalType().getTypePtr();
3181
3182 // FIXME: Consider using the C++ type mangling when we encounter a construct
3183 // that is incompatible with C.
3184
3185 switch (T->getTypeClass()) {
3186 case Type::Atomic:
3188 Ctx, OS, cast<AtomicType>(T)->getValueType());
3189
3190 case Type::LValueReference:
3191 OS << "R";
3193 cast<ReferenceType>(T)->getPointeeType());
3194 return;
3195 case Type::RValueReference:
3196 OS << "O";
3198 cast<ReferenceType>(T)->getPointeeType());
3199 return;
3200
3201 case Type::Pointer:
3202 // C11 6.7.6.1p2:
3203 // For two pointer types to be compatible, both shall be identically
3204 // qualified and both shall be pointers to compatible types.
3205 // FIXME: we should also consider pointee types.
3206 OS << "P";
3207 return;
3208
3209 case Type::ObjCObjectPointer:
3210 case Type::BlockPointer:
3211 OS << "P";
3212 return;
3213
3214 case Type::Complex:
3215 OS << "C";
3217 Ctx, OS, cast<ComplexType>(T)->getElementType());
3218
3219 case Type::VariableArray:
3220 case Type::ConstantArray:
3221 case Type::IncompleteArray:
3222 case Type::ArrayParameter:
3223 // C11 6.7.6.2p6:
3224 // For two array types to be compatible, both shall have compatible
3225 // element types, and if both size specifiers are present, and are integer
3226 // constant expressions, then both size specifiers shall have the same
3227 // constant value [...]
3228 //
3229 // So since ElemType[N] has to be compatible ElemType[], we can't encode the
3230 // width of the array.
3231 OS << "A";
3233 Ctx, OS, cast<ArrayType>(T)->getElementType());
3234
3235 case Type::ObjCInterface:
3236 case Type::ObjCObject:
3237 OS << "<objc_object>";
3238 return;
3239
3240 case Type::Enum: {
3241 // C11 6.7.2.2p4:
3242 // Each enumerated type shall be compatible with char, a signed integer
3243 // type, or an unsigned integer type.
3244 //
3245 // So we have to treat enum types as integers.
3246 QualType UnderlyingType = cast<EnumType>(T)->getDecl()->getIntegerType();
3248 Ctx, OS, UnderlyingType.isNull() ? Ctx.IntTy : UnderlyingType);
3249 }
3250
3251 case Type::FunctionNoProto:
3252 case Type::FunctionProto: {
3253 // C11 6.7.6.3p15:
3254 // For two function types to be compatible, both shall specify compatible
3255 // return types. Moreover, the parameter type lists, if both are present,
3256 // shall agree in the number of parameters and in the use of the ellipsis
3257 // terminator; corresponding parameters shall have compatible types.
3258 //
3259 // That paragraph goes on to describe how unprototyped functions are to be
3260 // handled, which we ignore here. Unprototyped function pointers are hashed
3261 // as though they were prototyped nullary functions since thats probably
3262 // what the user meant. This behavior is non-conforming.
3263 // FIXME: If we add a "custom discriminator" function type attribute we
3264 // should encode functions as their discriminators.
3265 OS << "F";
3266 const auto *FuncType = cast<FunctionType>(T);
3267 encodeTypeForFunctionPointerAuth(Ctx, OS, FuncType->getReturnType());
3268 if (const auto *FPT = dyn_cast<FunctionProtoType>(FuncType)) {
3269 for (QualType Param : FPT->param_types()) {
3270 Param = Ctx.getSignatureParameterType(Param);
3271 encodeTypeForFunctionPointerAuth(Ctx, OS, Param);
3272 }
3273 if (FPT->isVariadic())
3274 OS << "z";
3275 }
3276 OS << "E";
3277 return;
3278 }
3279
3280 case Type::MemberPointer: {
3281 OS << "M";
3282 const auto *MPT = T->castAs<MemberPointerType>();
3283 encodeTypeForFunctionPointerAuth(Ctx, OS, QualType(MPT->getClass(), 0));
3284 encodeTypeForFunctionPointerAuth(Ctx, OS, MPT->getPointeeType());
3285 return;
3286 }
3287 case Type::ExtVector:
3288 case Type::Vector:
3289 OS << "Dv" << Ctx.getTypeSizeInChars(T).getQuantity();
3290 break;
3291
3292 // Don't bother discriminating based on these types.
3293 case Type::Pipe:
3294 case Type::BitInt:
3295 case Type::ConstantMatrix:
3296 OS << "?";
3297 return;
3298
3299 case Type::Builtin: {
3300 const auto *BTy = T->castAs<BuiltinType>();
3301 switch (BTy->getKind()) {
3302#define SIGNED_TYPE(Id, SingletonId) \
3303 case BuiltinType::Id: \
3304 OS << "i"; \
3305 return;
3306#define UNSIGNED_TYPE(Id, SingletonId) \
3307 case BuiltinType::Id: \
3308 OS << "i"; \
3309 return;
3310#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
3311#define BUILTIN_TYPE(Id, SingletonId)
3312#include "clang/AST/BuiltinTypes.def"
3313 llvm_unreachable("placeholder types should not appear here.");
3314
3315 case BuiltinType::Half:
3316 OS << "Dh";
3317 return;
3318 case BuiltinType::Float:
3319 OS << "f";
3320 return;
3321 case BuiltinType::Double:
3322 OS << "d";
3323 return;
3324 case BuiltinType::LongDouble:
3325 OS << "e";
3326 return;
3327 case BuiltinType::Float16:
3328 OS << "DF16_";
3329 return;
3330 case BuiltinType::Float128:
3331 OS << "g";
3332 return;
3333
3334 case BuiltinType::Void:
3335 OS << "v";
3336 return;
3337
3338 case BuiltinType::ObjCId:
3339 case BuiltinType::ObjCClass:
3340 case BuiltinType::ObjCSel:
3341 case BuiltinType::NullPtr:
3342 OS << "P";
3343 return;
3344
3345 // Don't bother discriminating based on OpenCL types.
3346 case BuiltinType::OCLSampler:
3347 case BuiltinType::OCLEvent:
3348 case BuiltinType::OCLClkEvent:
3349 case BuiltinType::OCLQueue:
3350 case BuiltinType::OCLReserveID:
3351 case BuiltinType::BFloat16:
3352 case BuiltinType::VectorQuad:
3353 case BuiltinType::VectorPair:
3354 OS << "?";
3355 return;
3356
3357 // Don't bother discriminating based on these seldom-used types.
3358 case BuiltinType::Ibm128:
3359 return;
3360#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
3361 case BuiltinType::Id: \
3362 return;
3363#include "clang/Basic/OpenCLImageTypes.def"
3364#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
3365 case BuiltinType::Id: \
3366 return;
3367#include "clang/Basic/OpenCLExtensionTypes.def"
3368#define SVE_TYPE(Name, Id, SingletonId) \
3369 case BuiltinType::Id: \
3370 return;
3371#include "clang/Basic/AArch64SVEACLETypes.def"
3372#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
3373 case BuiltinType::Id: \
3374 return;
3375#include "clang/Basic/HLSLIntangibleTypes.def"
3376 case BuiltinType::Dependent:
3377 llvm_unreachable("should never get here");
3378 case BuiltinType::AMDGPUBufferRsrc:
3379 case BuiltinType::WasmExternRef:
3380#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
3381#include "clang/Basic/RISCVVTypes.def"
3382 llvm_unreachable("not yet implemented");
3383 }
3384 llvm_unreachable("should never get here");
3385 }
3386 case Type::Record: {
3387 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
3388 const IdentifierInfo *II = RD->getIdentifier();
3389
3390 // In C++, an immediate typedef of an anonymous struct or union
3391 // is considered to name it for ODR purposes, but C's specification
3392 // of type compatibility does not have a similar rule. Using the typedef
3393 // name in function type discriminators anyway, as we do here,
3394 // therefore technically violates the C standard: two function pointer
3395 // types defined in terms of two typedef'd anonymous structs with
3396 // different names are formally still compatible, but we are assigning
3397 // them different discriminators and therefore incompatible ABIs.
3398 //
3399 // This is a relatively minor violation that significantly improves
3400 // discrimination in some cases and has not caused problems in
3401 // practice. Regardless, it is now part of the ABI in places where
3402 // function type discrimination is used, and it can no longer be
3403 // changed except on new platforms.
3404
3405 if (!II)
3406 if (const TypedefNameDecl *Typedef = RD->getTypedefNameForAnonDecl())
3407 II = Typedef->getDeclName().getAsIdentifierInfo();
3408
3409 if (!II) {
3410 OS << "<anonymous_record>";
3411 return;
3412 }
3413 OS << II->getLength() << II->getName();
3414 return;
3415 }
3416 case Type::DeducedTemplateSpecialization:
3417 case Type::Auto:
3418#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3419#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3420#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3421#define ABSTRACT_TYPE(Class, Base)
3422#define TYPE(Class, Base)
3423#include "clang/AST/TypeNodes.inc"
3424 llvm_unreachable("unexpected non-canonical or dependent type!");
3425 return;
3426 }
3427}
3428
3430 assert(!T->isDependentType() &&
3431 "cannot compute type discriminator of a dependent type");
3432
3433 SmallString<256> Str;
3434 llvm::raw_svector_ostream Out(Str);
3435
3437 T = T->getPointeeType();
3438
3439 if (T->isFunctionType()) {
3441 } else {
3442 T = T.getUnqualifiedType();
3443 std::unique_ptr<MangleContext> MC(createMangleContext());
3444 MC->mangleCanonicalTypeName(T, Out);
3445 }
3446
3447 return llvm::getPointerAuthStableSipHash(Str);
3448}
3449
3451 Qualifiers::GC GCAttr) const {
3452 QualType CanT = getCanonicalType(T);
3453 if (CanT.getObjCGCAttr() == GCAttr)
3454 return T;
3455
3456 if (const auto *ptr = T->getAs<PointerType>()) {
3457 QualType Pointee = ptr->getPointeeType();
3458 if (Pointee->isAnyPointerType()) {
3459 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
3460 return getPointerType(ResultType);
3461 }
3462 }
3463
3464 // If we are composing extended qualifiers together, merge together
3465 // into one ExtQuals node.
3466 QualifierCollector Quals;
3467 const Type *TypeNode = Quals.strip(T);
3468
3469 // If this type already has an ObjCGC specified, it cannot get
3470 // another one.
3471 assert(!Quals.hasObjCGCAttr() &&
3472 "Type cannot have multiple ObjCGCs!");
3473 Quals.addObjCGCAttr(GCAttr);
3474
3475 return getExtQualType(TypeNode, Quals);
3476}
3477
3479 if (const PointerType *Ptr = T->getAs<PointerType>()) {
3480 QualType Pointee = Ptr->getPointeeType();
3481 if (isPtrSizeAddressSpace(Pointee.getAddressSpace())) {
3482 return getPointerType(removeAddrSpaceQualType(Pointee));
3483 }
3484 }
3485 return T;
3486}
3487
3489 QualType WrappedTy, Expr *CountExpr, bool CountInBytes, bool OrNull,
3490 ArrayRef<TypeCoupledDeclRefInfo> DependentDecls) const {
3491 assert(WrappedTy->isPointerType() || WrappedTy->isArrayType());
3492
3493 llvm::FoldingSetNodeID ID;
3494 CountAttributedType::Profile(ID, WrappedTy, CountExpr, CountInBytes, OrNull);
3495
3496 void *InsertPos = nullptr;
3497 CountAttributedType *CATy =
3498 CountAttributedTypes.FindNodeOrInsertPos(ID, InsertPos);
3499 if (CATy)
3500 return QualType(CATy, 0);
3501
3502 QualType CanonTy = getCanonicalType(WrappedTy);
3503 size_t Size = CountAttributedType::totalSizeToAlloc<TypeCoupledDeclRefInfo>(
3504 DependentDecls.size());
3506 new (CATy) CountAttributedType(WrappedTy, CanonTy, CountExpr, CountInBytes,
3507 OrNull, DependentDecls);
3508 Types.push_back(CATy);
3509 CountAttributedTypes.InsertNode(CATy, InsertPos);
3510
3511 return QualType(CATy, 0);
3512}
3513
3515 FunctionType::ExtInfo Info) {
3516 if (T->getExtInfo() == Info)
3517 return T;
3518
3520 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
3521 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
3522 } else {
3523 const auto *FPT = cast<FunctionProtoType>(T);
3524 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
3525 EPI.ExtInfo = Info;
3526 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
3527 }
3528
3529 return cast<FunctionType>(Result.getTypePtr());
3530}
3531
3533 QualType ResultType) {
3534 FD = FD->getMostRecentDecl();
3535 while (true) {
3536 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
3537 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
3538 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
3539 if (FunctionDecl *Next = FD->getPreviousDecl())
3540 FD = Next;
3541 else
3542 break;
3543 }
3545 L->DeducedReturnType(FD, ResultType);
3546}
3547
3548/// Get a function type and produce the equivalent function type with the
3549/// specified exception specification. Type sugar that can be present on a
3550/// declaration of a function with an exception specification is permitted
3551/// and preserved. Other type sugar (for instance, typedefs) is not.
3553 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const {
3554 // Might have some parens.
3555 if (const auto *PT = dyn_cast<ParenType>(Orig))
3556 return getParenType(
3557 getFunctionTypeWithExceptionSpec(PT->getInnerType(), ESI));
3558
3559 // Might be wrapped in a macro qualified type.
3560 if (const auto *MQT = dyn_cast<MacroQualifiedType>(Orig))
3561 return getMacroQualifiedType(
3562 getFunctionTypeWithExceptionSpec(MQT->getUnderlyingType(), ESI),
3563 MQT->getMacroIdentifier());
3564
3565 // Might have a calling-convention attribute.
3566 if (const auto *AT = dyn_cast<AttributedType>(Orig))
3567 return getAttributedType(
3568 AT->getAttrKind(),
3569 getFunctionTypeWithExceptionSpec(AT->getModifiedType(), ESI),
3570 getFunctionTypeWithExceptionSpec(AT->getEquivalentType(), ESI));
3571
3572 // Anything else must be a function type. Rebuild it with the new exception
3573 // specification.
3574 const auto *Proto = Orig->castAs<FunctionProtoType>();
3575 return getFunctionType(
3576 Proto->getReturnType(), Proto->getParamTypes(),
3577 Proto->getExtProtoInfo().withExceptionSpec(ESI));
3578}
3579
3581 QualType U) const {
3582 return hasSameType(T, U) ||
3583 (getLangOpts().CPlusPlus17 &&
3586}
3587
3589 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3590 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3591 SmallVector<QualType, 16> Args(Proto->param_types().size());
3592 for (unsigned i = 0, n = Args.size(); i != n; ++i)
3593 Args[i] = removePtrSizeAddrSpace(Proto->param_types()[i]);
3594 return getFunctionType(RetTy, Args, Proto->getExtProtoInfo());
3595 }
3596
3597 if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) {
3598 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3599 return getFunctionNoProtoType(RetTy, Proto->getExtInfo());
3600 }
3601
3602 return T;
3603}
3604
3606 return hasSameType(T, U) ||
3609}
3610
3613 bool AsWritten) {
3614 // Update the type.
3615 QualType Updated =
3617 FD->setType(Updated);
3618
3619 if (!AsWritten)
3620 return;
3621
3622 // Update the type in the type source information too.
3623 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
3624 // If the type and the type-as-written differ, we may need to update
3625 // the type-as-written too.
3626 if (TSInfo->getType() != FD->getType())
3627 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
3628
3629 // FIXME: When we get proper type location information for exceptions,
3630 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
3631 // up the TypeSourceInfo;
3632 assert(TypeLoc::getFullDataSizeForType(Updated) ==
3633 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
3634 "TypeLoc size mismatch from updating exception specification");
3635 TSInfo->overrideType(Updated);
3636 }
3637}
3638
3639/// getComplexType - Return the uniqued reference to the type for a complex
3640/// number with the specified element type.
3642 // Unique pointers, to guarantee there is only one pointer of a particular
3643 // structure.
3644 llvm::FoldingSetNodeID ID;
3646
3647 void *InsertPos = nullptr;
3648 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
3649 return QualType(CT, 0);
3650
3651 // If the pointee type isn't canonical, this won't be a canonical type either,
3652 // so fill in the canonical type field.
3653 QualType Canonical;
3654 if (!T.isCanonical()) {
3655 Canonical = getComplexType(getCanonicalType(T));
3656
3657 // Get the new insert position for the node we care about.
3658 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
3659 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3660 }
3661 auto *New = new (*this, alignof(ComplexType)) ComplexType(T, Canonical);
3662 Types.push_back(New);
3663 ComplexTypes.InsertNode(New, InsertPos);
3664 return QualType(New, 0);
3665}
3666
3667/// getPointerType - Return the uniqued reference to the type for a pointer to
3668/// the specified type.
3670 // Unique pointers, to guarantee there is only one pointer of a particular
3671 // structure.
3672 llvm::FoldingSetNodeID ID;
3674
3675 void *InsertPos = nullptr;
3676 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3677 return QualType(PT, 0);
3678
3679 // If the pointee type isn't canonical, this won't be a canonical type either,
3680 // so fill in the canonical type field.
3681 QualType Canonical;
3682 if (!T.isCanonical()) {
3683 Canonical = getPointerType(getCanonicalType(T));
3684
3685 // Get the new insert position for the node we care about.
3686 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3687 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3688 }
3689 auto *New = new (*this, alignof(PointerType)) PointerType(T, Canonical);
3690 Types.push_back(New);
3691 PointerTypes.InsertNode(New, InsertPos);
3692 return QualType(New, 0);
3693}
3694
3696 llvm::FoldingSetNodeID ID;
3697 AdjustedType::Profile(ID, Orig, New);
3698 void *InsertPos = nullptr;
3699 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3700 if (AT)
3701 return QualType(AT, 0);
3702
3703 QualType Canonical = getCanonicalType(New);
3704
3705 // Get the new insert position for the node we care about.
3706 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3707 assert(!AT && "Shouldn't be in the map!");
3708
3709 AT = new (*this, alignof(AdjustedType))
3710 AdjustedType(Type::Adjusted, Orig, New, Canonical);
3711 Types.push_back(AT);
3712 AdjustedTypes.InsertNode(AT, InsertPos);
3713 return QualType(AT, 0);
3714}
3715
3717 llvm::FoldingSetNodeID ID;
3718 AdjustedType::Profile(ID, Orig, Decayed);
3719 void *InsertPos = nullptr;
3720 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3721 if (AT)
3722 return QualType(AT, 0);
3723
3724 QualType Canonical = getCanonicalType(Decayed);
3725
3726 // Get the new insert position for the node we care about.
3727 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3728 assert(!AT && "Shouldn't be in the map!");
3729
3730 AT = new (*this, alignof(DecayedType)) DecayedType(Orig, Decayed, Canonical);
3731 Types.push_back(AT);
3732 AdjustedTypes.InsertNode(AT, InsertPos);
3733 return QualType(AT, 0);
3734}
3735
3737 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
3738
3739 QualType Decayed;
3740
3741 // C99 6.7.5.3p7:
3742 // A declaration of a parameter as "array of type" shall be
3743 // adjusted to "qualified pointer to type", where the type
3744 // qualifiers (if any) are those specified within the [ and ] of
3745 // the array type derivation.
3746 if (T->isArrayType())
3747 Decayed = getArrayDecayedType(T);
3748
3749 // C99 6.7.5.3p8:
3750 // A declaration of a parameter as "function returning type"
3751 // shall be adjusted to "pointer to function returning type", as
3752 // in 6.3.2.1.
3753 if (T->isFunctionType())
3754 Decayed = getPointerType(T);
3755
3756 return getDecayedType(T, Decayed);
3757}
3758
3760 if (Ty->isArrayParameterType())
3761 return Ty;
3762 assert(Ty->isConstantArrayType() && "Ty must be an array type.");
3763 const auto *ATy = cast<ConstantArrayType>(Ty);
3764 llvm::FoldingSetNodeID ID;
3765 ATy->Profile(ID, *this, ATy->getElementType(), ATy->getZExtSize(),
3766 ATy->getSizeExpr(), ATy->getSizeModifier(),
3767 ATy->getIndexTypeQualifiers().getAsOpaqueValue());
3768 void *InsertPos = nullptr;
3769 ArrayParameterType *AT =
3770 ArrayParameterTypes.FindNodeOrInsertPos(ID, InsertPos);
3771 if (AT)
3772 return QualType(AT, 0);
3773
3774 QualType Canonical;
3775 if (!Ty.isCanonical()) {
3776 Canonical = getArrayParameterType(getCanonicalType(Ty));
3777
3778 // Get the new insert position for the node we care about.
3779 AT = ArrayParameterTypes.FindNodeOrInsertPos(ID, InsertPos);
3780 assert(!AT && "Shouldn't be in the map!");
3781 }
3782
3783 AT = new (*this, alignof(ArrayParameterType))
3784 ArrayParameterType(ATy, Canonical);
3785 Types.push_back(AT);
3786 ArrayParameterTypes.InsertNode(AT, InsertPos);
3787 return QualType(AT, 0);
3788}
3789
3790/// getBlockPointerType - Return the uniqued reference to the type for
3791/// a pointer to the specified block.
3793 assert(T->isFunctionType() && "block of function types only");
3794 // Unique pointers, to guarantee there is only one block of a particular
3795 // structure.
3796 llvm::FoldingSetNodeID ID;
3798
3799 void *InsertPos = nullptr;
3800 if (BlockPointerType *PT =
3801 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3802 return QualType(PT, 0);
3803
3804 // If the block pointee type isn't canonical, this won't be a canonical
3805 // type either so fill in the canonical type field.
3806 QualType Canonical;
3807 if (!T.isCanonical()) {
3809
3810 // Get the new insert position for the node we care about.
3811 BlockPointerType *NewIP =
3812 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3813 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3814 }
3815 auto *New =
3816 new (*this, alignof(BlockPointerType)) BlockPointerType(T, Canonical);
3817 Types.push_back(New);
3818 BlockPointerTypes.InsertNode(New, InsertPos);
3819 return QualType(New, 0);
3820}
3821
3822/// getLValueReferenceType - Return the uniqued reference to the type for an
3823/// lvalue reference to the specified type.
3825ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
3826 assert((!T->isPlaceholderType() ||
3827 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
3828 "Unresolved placeholder type");
3829
3830 // Unique pointers, to guarantee there is only one pointer of a particular
3831 // structure.
3832 llvm::FoldingSetNodeID ID;
3833 ReferenceType::Profile(ID, T, SpelledAsLValue);
3834
3835 void *InsertPos = nullptr;
3836 if (LValueReferenceType *RT =
3837 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
3838 return QualType(RT, 0);
3839
3840 const auto *InnerRef = T->getAs<ReferenceType>();
3841
3842 // If the referencee type isn't canonical, this won't be a canonical type
3843 // either, so fill in the canonical type field.
3844 QualType Canonical;
3845 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
3846 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3847 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
3848
3849 // Get the new insert position for the node we care about.
3850 LValueReferenceType *NewIP =
3851 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
3852 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3853 }
3854
3855 auto *New = new (*this, alignof(LValueReferenceType))
3856 LValueReferenceType(T, Canonical, SpelledAsLValue);
3857 Types.push_back(New);
3858 LValueReferenceTypes.InsertNode(New, InsertPos);
3859
3860 return QualType(New, 0);
3861}
3862
3863/// getRValueReferenceType - Return the uniqued reference to the type for an
3864/// rvalue reference to the specified type.
3866 assert((!T->isPlaceholderType() ||
3867 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
3868 "Unresolved placeholder type");
3869
3870 // Unique pointers, to guarantee there is only one pointer of a particular
3871 // structure.
3872 llvm::FoldingSetNodeID ID;
3873 ReferenceType::Profile(ID, T, false);
3874
3875 void *InsertPos = nullptr;
3876 if (RValueReferenceType *RT =
3877 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
3878 return QualType(RT, 0);
3879
3880 const auto *InnerRef = T->getAs<ReferenceType>();
3881
3882 // If the referencee type isn't canonical, this won't be a canonical type
3883 // either, so fill in the canonical type field.
3884 QualType Canonical;
3885 if (InnerRef || !T.isCanonical()) {
3886 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3887 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
3888
3889 // Get the new insert position for the node we care about.
3890 RValueReferenceType *NewIP =
3891 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
3892 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3893 }
3894
3895 auto *New = new (*this, alignof(RValueReferenceType))
3896 RValueReferenceType(T, Canonical);
3897 Types.push_back(New);
3898 RValueReferenceTypes.InsertNode(New, InsertPos);
3899 return QualType(New, 0);
3900}
3901
3902/// getMemberPointerType - Return the uniqued reference to the type for a
3903/// member pointer to the specified type, in the specified class.
3905 // Unique pointers, to guarantee there is only one pointer of a particular
3906 // structure.
3907 llvm::FoldingSetNodeID ID;
3908 MemberPointerType::Profile(ID, T, Cls);
3909
3910 void *InsertPos = nullptr;
3911 if (MemberPointerType *PT =
3912 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3913 return QualType(PT, 0);
3914
3915 // If the pointee or class type isn't canonical, this won't be a canonical
3916 // type either, so fill in the canonical type field.
3917 QualType Canonical;
3918 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
3920
3921 // Get the new insert position for the node we care about.
3922 MemberPointerType *NewIP =
3923 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3924 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3925 }
3926 auto *New = new (*this, alignof(MemberPointerType))
3927 MemberPointerType(T, Cls, Canonical);
3928 Types.push_back(New);
3929 MemberPointerTypes.InsertNode(New, InsertPos);
3930 return QualType(New, 0);
3931}
3932
3933/// getConstantArrayType - Return the unique reference to the type for an
3934/// array of the specified element type.
3936 const llvm::APInt &ArySizeIn,
3937 const Expr *SizeExpr,
3939 unsigned IndexTypeQuals) const {
3940 assert((EltTy->isDependentType() ||
3941 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
3942 "Constant array of VLAs is illegal!");
3943
3944 // We only need the size as part of the type if it's instantiation-dependent.
3945 if (SizeExpr && !SizeExpr->isInstantiationDependent())
3946 SizeExpr = nullptr;
3947
3948 // Convert the array size into a canonical width matching the pointer size for
3949 // the target.
3950 llvm::APInt ArySize(ArySizeIn);
3951 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
3952
3953 llvm::FoldingSetNodeID ID;
3954 ConstantArrayType::Profile(ID, *this, EltTy, ArySize.getZExtValue(), SizeExpr,
3955 ASM, IndexTypeQuals);
3956
3957 void *InsertPos = nullptr;
3958 if (ConstantArrayType *ATP =
3959 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
3960 return QualType(ATP, 0);
3961
3962 // If the element type isn't canonical or has qualifiers, or the array bound
3963 // is instantiation-dependent, this won't be a canonical type either, so fill
3964 // in the canonical type field.
3965 QualType Canon;
3966 // FIXME: Check below should look for qualifiers behind sugar.
3967 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) {
3968 SplitQualType canonSplit = getCanonicalType(EltTy).split();
3969 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr,
3970 ASM, IndexTypeQuals);
3971 Canon = getQualifiedType(Canon, canonSplit.Quals);
3972
3973 // Get the new insert position for the node we care about.
3974 ConstantArrayType *NewIP =
3975 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
3976 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3977 }
3978
3979 auto *New = ConstantArrayType::Create(*this, EltTy, Canon, ArySize, SizeExpr,
3980 ASM, IndexTypeQuals);
3981 ConstantArrayTypes.InsertNode(New, InsertPos);
3982 Types.push_back(New);
3983 return QualType(New, 0);
3984}
3985
3986/// getVariableArrayDecayedType - Turns the given type, which may be
3987/// variably-modified, into the corresponding type with all the known
3988/// sizes replaced with [*].
3990 // Vastly most common case.
3991 if (!type->isVariablyModifiedType()) return type;
3992
3993 QualType result;
3994
3995 SplitQualType split = type.getSplitDesugaredType();
3996 const Type *ty = split.Ty;
3997 switch (ty->getTypeClass()) {
3998#define TYPE(Class, Base)
3999#define ABSTRACT_TYPE(Class, Base)
4000#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4001#include "clang/AST/TypeNodes.inc"
4002 llvm_unreachable("didn't desugar past all non-canonical types?");
4003
4004 // These types should never be variably-modified.
4005 case Type::Builtin:
4006 case Type::Complex:
4007 case Type::Vector:
4008 case Type::DependentVector:
4009 case Type::ExtVector:
4010 case Type::DependentSizedExtVector:
4011 case Type::ConstantMatrix:
4012 case Type::DependentSizedMatrix:
4013 case Type::DependentAddressSpace:
4014 case Type::ObjCObject:
4015 case Type::ObjCInterface:
4016 case Type::ObjCObjectPointer:
4017 case Type::Record:
4018 case Type::Enum:
4019 case Type::UnresolvedUsing:
4020 case Type::TypeOfExpr:
4021 case Type::TypeOf:
4022 case Type::Decltype:
4023 case Type::UnaryTransform:
4024 case Type::DependentName:
4025 case Type::InjectedClassName:
4026 case Type::TemplateSpecialization:
4027 case Type::DependentTemplateSpecialization:
4028 case Type::TemplateTypeParm:
4029 case Type::SubstTemplateTypeParmPack:
4030 case Type::Auto:
4031 case Type::DeducedTemplateSpecialization:
4032 case Type::PackExpansion:
4033 case Type::PackIndexing:
4034 case Type::BitInt:
4035 case Type::DependentBitInt:
4036 case Type::ArrayParameter:
4037 llvm_unreachable("type should never be variably-modified");
4038
4039 // These types can be variably-modified but should never need to
4040 // further decay.
4041 case Type::FunctionNoProto:
4042 case Type::FunctionProto:
4043 case Type::BlockPointer:
4044 case Type::MemberPointer:
4045 case Type::Pipe:
4046 return type;
4047
4048 // These types can be variably-modified. All these modifications
4049 // preserve structure except as noted by comments.
4050 // TODO: if we ever care about optimizing VLAs, there are no-op
4051 // optimizations available here.
4052 case Type::Pointer:
4054 cast<PointerType>(ty)->getPointeeType()));
4055 break;
4056
4057 case Type::LValueReference: {
4058 const auto *lv = cast<LValueReferenceType>(ty);
4059 result = getLValueReferenceType(
4060 getVariableArrayDecayedType(lv->getPointeeType()),
4061 lv->isSpelledAsLValue());
4062 break;
4063 }
4064
4065 case Type::RValueReference: {
4066 const auto *lv = cast<RValueReferenceType>(ty);
4067 result = getRValueReferenceType(
4068 getVariableArrayDecayedType(lv->getPointeeType()));
4069 break;
4070 }
4071
4072 case Type::Atomic: {
4073 const auto *at = cast<AtomicType>(ty);
4074 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
4075 break;
4076 }
4077
4078 case Type::ConstantArray: {
4079 const auto *cat = cast<ConstantArrayType>(ty);
4080 result = getConstantArrayType(
4081 getVariableArrayDecayedType(cat->getElementType()),
4082 cat->getSize(),
4083 cat->getSizeExpr(),
4084 cat->getSizeModifier(),
4085 cat->getIndexTypeCVRQualifiers());
4086 break;
4087 }
4088
4089 case Type::DependentSizedArray: {
4090 const auto *dat = cast<DependentSizedArrayType>(ty);
4092 getVariableArrayDecayedType(dat->getElementType()),
4093 dat->getSizeExpr(),
4094 dat->getSizeModifier(),
4095 dat->getIndexTypeCVRQualifiers(),
4096 dat->getBracketsRange());
4097 break;
4098 }
4099
4100 // Turn incomplete types into [*] types.
4101 case Type::IncompleteArray: {
4102 const auto *iat = cast<IncompleteArrayType>(ty);
4103 result =
4105 /*size*/ nullptr, ArraySizeModifier::Normal,
4106 iat->getIndexTypeCVRQualifiers(), SourceRange());
4107 break;
4108 }
4109
4110 // Turn VLA types into [*] types.
4111 case Type::VariableArray: {
4112 const auto *vat = cast<VariableArrayType>(ty);
4113 result = getVariableArrayType(
4114 getVariableArrayDecayedType(vat->getElementType()),
4115 /*size*/ nullptr, ArraySizeModifier::Star,
4116 vat->getIndexTypeCVRQualifiers(), vat->getBracketsRange());
4117 break;
4118 }
4119 }
4120
4121 // Apply the top-level qualifiers from the original.
4122 return getQualifiedType(result, split.Quals);
4123}
4124
4125/// getVariableArrayType - Returns a non-unique reference to the type for a
4126/// variable array of the specified element type.
4129 unsigned IndexTypeQuals,
4130 SourceRange Brackets) const {
4131 // Since we don't unique expressions, it isn't possible to unique VLA's
4132 // that have an expression provided for their size.
4133 QualType Canon;
4134
4135 // Be sure to pull qualifiers off the element type.
4136 // FIXME: Check below should look for qualifiers behind sugar.
4137 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
4138 SplitQualType canonSplit = getCanonicalType(EltTy).split();
4139 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
4140 IndexTypeQuals, Brackets);
4141 Canon = getQualifiedType(Canon, canonSplit.Quals);
4142 }
4143
4144 auto *New = new (*this, alignof(VariableArrayType))
4145 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
4146
4147 VariableArrayTypes.push_back(New);
4148 Types.push_back(New);
4149 return QualType(New, 0);
4150}
4151
4152/// getDependentSizedArrayType - Returns a non-unique reference to
4153/// the type for a dependently-sized array of the specified element
4154/// type.
4156 Expr *numElements,
4158 unsigned elementTypeQuals,
4159 SourceRange brackets) const {
4160 assert((!numElements || numElements->isTypeDependent() ||
4161 numElements->isValueDependent()) &&
4162 "Size must be type- or value-dependent!");
4163
4164 SplitQualType canonElementType = getCanonicalType(elementType).split();
4165
4166 void *insertPos = nullptr;
4167 llvm::FoldingSetNodeID ID;
4169 ID, *this, numElements ? QualType(canonElementType.Ty, 0) : elementType,
4170 ASM, elementTypeQuals, numElements);
4171
4172 // Look for an existing type with these properties.
4173 DependentSizedArrayType *canonTy =
4174 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
4175
4176 // Dependently-sized array types that do not have a specified number
4177 // of elements will have their sizes deduced from a dependent
4178 // initializer.
4179 if (!numElements) {
4180 if (canonTy)
4181 return QualType(canonTy, 0);
4182
4183 auto *newType = new (*this, alignof(DependentSizedArrayType))
4184 DependentSizedArrayType(elementType, QualType(), numElements, ASM,
4185 elementTypeQuals, brackets);
4186 DependentSizedArrayTypes.InsertNode(newType, insertPos);
4187 Types.push_back(newType);
4188 return QualType(newType, 0);
4189 }
4190
4191 // If we don't have one, build one.
4192 if (!canonTy) {
4193 canonTy = new (*this, alignof(DependentSizedArrayType))
4194 DependentSizedArrayType(QualType(canonElementType.Ty, 0), QualType(),
4195 numElements, ASM, elementTypeQuals, brackets);
4196 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
4197 Types.push_back(canonTy);
4198 }
4199
4200 // Apply qualifiers from the element type to the array.
4201 QualType canon = getQualifiedType(QualType(canonTy,0),
4202 canonElementType.Quals);
4203
4204 // If we didn't need extra canonicalization for the element type or the size
4205 // expression, then just use that as our result.
4206 if (QualType(canonElementType.Ty, 0) == elementType &&
4207 canonTy->getSizeExpr() == numElements)
4208 return canon;
4209
4210 // Otherwise, we need to build a type which follows the spelling
4211 // of the element type.
4212 auto *sugaredType = new (*this, alignof(DependentSizedArrayType))
4213 DependentSizedArrayType(elementType, canon, numElements, ASM,
4214 elementTypeQuals, brackets);
4215 Types.push_back(sugaredType);
4216 return QualType(sugaredType, 0);
4217}
4218
4221 unsigned elementTypeQuals) const {
4222 llvm::FoldingSetNodeID ID;
4223 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
4224
4225 void *insertPos = nullptr;
4226 if (IncompleteArrayType *iat =
4227 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
4228 return QualType(iat, 0);
4229
4230 // If the element type isn't canonical, this won't be a canonical type
4231 // either, so fill in the canonical type field. We also have to pull
4232 // qualifiers off the element type.
4233 QualType canon;
4234
4235 // FIXME: Check below should look for qualifiers behind sugar.
4236 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
4237 SplitQualType canonSplit = getCanonicalType(elementType).split();
4238 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
4239 ASM, elementTypeQuals);
4240 canon = getQualifiedType(canon, canonSplit.Quals);
4241
4242 // Get the new insert position for the node we care about.
4243 IncompleteArrayType *existing =
4244 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
4245 assert(!existing && "Shouldn't be in the map!"); (void) existing;
4246 }
4247
4248 auto *newType = new (*this, alignof(IncompleteArrayType))
4249 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
4250
4251 IncompleteArrayTypes.InsertNode(newType, insertPos);
4252 Types.push_back(newType);
4253 return QualType(newType, 0);
4254}
4255
4258#define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS) \
4259 {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount::getScalable(ELTS), \
4260 NUMVECTORS};
4261
4262#define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS) \
4263 {ELTTY, llvm::ElementCount::getScalable(ELTS), NUMVECTORS};
4264
4265 switch (Ty->getKind()) {
4266 default:
4267 llvm_unreachable("Unsupported builtin vector type");
4268 case BuiltinType::SveInt8:
4269 return SVE_INT_ELTTY(8, 16, true, 1);
4270 case BuiltinType::SveUint8:
4271 return SVE_INT_ELTTY(8, 16, false, 1);
4272 case BuiltinType::SveInt8x2:
4273 return SVE_INT_ELTTY(8, 16, true, 2);
4274 case BuiltinType::SveUint8x2:
4275 return SVE_INT_ELTTY(8, 16, false, 2);
4276 case BuiltinType::SveInt8x3:
4277 return SVE_INT_ELTTY(8, 16, true, 3);
4278 case BuiltinType::SveUint8x3:
4279 return SVE_INT_ELTTY(8, 16, false, 3);
4280 case BuiltinType::SveInt8x4:
4281 return SVE_INT_ELTTY(8, 16, true, 4);
4282 case BuiltinType::SveUint8x4:
4283 return SVE_INT_ELTTY(8, 16, false, 4);
4284 case BuiltinType::SveInt16:
4285 return SVE_INT_ELTTY(16, 8, true, 1);
4286 case BuiltinType::SveUint16:
4287 return SVE_INT_ELTTY(16, 8, false, 1);
4288 case BuiltinType::SveInt16x2:
4289 return SVE_INT_ELTTY(16, 8, true, 2);
4290 case BuiltinType::SveUint16x2:
4291 return SVE_INT_ELTTY(16, 8, false, 2);
4292 case BuiltinType::SveInt16x3:
4293 return SVE_INT_ELTTY(16, 8, true, 3);
4294 case BuiltinType::SveUint16x3:
4295 return SVE_INT_ELTTY(16, 8, false, 3);
4296 case BuiltinType::SveInt16x4:
4297 return SVE_INT_ELTTY(16, 8, true, 4);
4298 case BuiltinType::SveUint16x4:
4299 return SVE_INT_ELTTY(16, 8, false, 4);
4300 case BuiltinType::SveInt32:
4301 return SVE_INT_ELTTY(32, 4, true, 1);
4302 case BuiltinType::SveUint32:
4303 return SVE_INT_ELTTY(32, 4, false, 1);
4304 case BuiltinType::SveInt32x2:
4305 return SVE_INT_ELTTY(32, 4, true, 2);
4306 case BuiltinType::SveUint32x2:
4307 return SVE_INT_ELTTY(32, 4, false, 2);
4308 case BuiltinType::SveInt32x3:
4309 return SVE_INT_ELTTY(32, 4, true, 3);
4310 case BuiltinType::SveUint32x3:
4311 return SVE_INT_ELTTY(32, 4, false, 3);
4312 case BuiltinType::SveInt32x4:
4313 return SVE_INT_ELTTY(32, 4, true, 4);
4314 case BuiltinType::SveUint32x4:
4315 return SVE_INT_ELTTY(32, 4, false, 4);
4316 case BuiltinType::SveInt64:
4317 return SVE_INT_ELTTY(64, 2, true, 1);
4318 case BuiltinType::SveUint64:
4319 return SVE_INT_ELTTY(64, 2, false, 1);
4320 case BuiltinType::SveInt64x2:
4321 return SVE_INT_ELTTY(64, 2, true, 2);
4322 case BuiltinType::SveUint64x2:
4323 return SVE_INT_ELTTY(64, 2, false, 2);
4324 case BuiltinType::SveInt64x3:
4325 return SVE_INT_ELTTY(64, 2, true, 3);
4326 case BuiltinType::SveUint64x3:
4327 return SVE_INT_ELTTY(64, 2, false, 3);
4328 case BuiltinType::SveInt64x4:
4329 return SVE_INT_ELTTY(64, 2, true, 4);
4330 case BuiltinType::SveUint64x4:
4331 return SVE_INT_ELTTY(64, 2, false, 4);
4332 case BuiltinType::SveBool:
4333 return SVE_ELTTY(BoolTy, 16, 1);
4334 case BuiltinType::SveBoolx2:
4335 return SVE_ELTTY(BoolTy, 16, 2);
4336 case BuiltinType::SveBoolx4:
4337 return SVE_ELTTY(BoolTy, 16, 4);
4338 case BuiltinType::SveFloat16:
4339 return SVE_ELTTY(HalfTy, 8, 1);
4340 case BuiltinType::SveFloat16x2:
4341 return SVE_ELTTY(HalfTy, 8, 2);
4342 case BuiltinType::SveFloat16x3:
4343 return SVE_ELTTY(HalfTy, 8, 3);
4344 case BuiltinType::SveFloat16x4:
4345 return SVE_ELTTY(HalfTy, 8, 4);
4346 case BuiltinType::SveFloat32:
4347 return SVE_ELTTY(FloatTy, 4, 1);
4348 case BuiltinType::SveFloat32x2:
4349 return SVE_ELTTY(FloatTy, 4, 2);
4350 case BuiltinType::SveFloat32x3:
4351 return SVE_ELTTY(FloatTy, 4, 3);
4352 case BuiltinType::SveFloat32x4:
4353 return SVE_ELTTY(FloatTy, 4, 4);
4354 case BuiltinType::SveFloat64:
4355 return SVE_ELTTY(DoubleTy, 2, 1);
4356 case BuiltinType::SveFloat64x2:
4357 return SVE_ELTTY(DoubleTy, 2, 2);
4358 case BuiltinType::SveFloat64x3:
4359 return SVE_ELTTY(DoubleTy, 2, 3);
4360 case BuiltinType::SveFloat64x4:
4361 return SVE_ELTTY(DoubleTy, 2, 4);
4362 case BuiltinType::SveBFloat16:
4363 return SVE_ELTTY(BFloat16Ty, 8, 1);
4364 case BuiltinType::SveBFloat16x2:
4365 return SVE_ELTTY(BFloat16Ty, 8, 2);
4366 case BuiltinType::SveBFloat16x3:
4367 return SVE_ELTTY(BFloat16Ty, 8, 3);
4368 case BuiltinType::SveBFloat16x4:
4369 return SVE_ELTTY(BFloat16Ty, 8, 4);
4370#define RVV_VECTOR_TYPE_INT(Name, Id, SingletonId, NumEls, ElBits, NF, \
4371 IsSigned) \
4372 case BuiltinType::Id: \
4373 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4374 llvm::ElementCount::getScalable(NumEls), NF};
4375#define RVV_VECTOR_TYPE_FLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4376 case BuiltinType::Id: \
4377 return {ElBits == 16 ? Float16Ty : (ElBits == 32 ? FloatTy : DoubleTy), \
4378 llvm::ElementCount::getScalable(NumEls), NF};
4379#define RVV_VECTOR_TYPE_BFLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4380 case BuiltinType::Id: \
4381 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4382#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4383 case BuiltinType::Id: \
4384 return {BoolTy, llvm::ElementCount::getScalable(NumEls), 1};
4385#include "clang/Basic/RISCVVTypes.def"
4386 }
4387}
4388
4389/// getExternrefType - Return a WebAssembly externref type, which represents an
4390/// opaque reference to a host value.
4392 if (Target->getTriple().isWasm() && Target->hasFeature("reference-types")) {
4393#define WASM_REF_TYPE(Name, MangledName, Id, SingletonId, AS) \
4394 if (BuiltinType::Id == BuiltinType::WasmExternRef) \
4395 return SingletonId;
4396#include "clang/Basic/WebAssemblyReferenceTypes.def"
4397 }
4398 llvm_unreachable(
4399 "shouldn't try to generate type externref outside WebAssembly target");
4400}
4401
4402/// getScalableVectorType - Return the unique reference to a scalable vector
4403/// type of the specified element type and size. VectorType must be a built-in
4404/// type.
4406 unsigned NumFields) const {
4407 if (Target->hasAArch64SVETypes()) {
4408 uint64_t EltTySize = getTypeSize(EltTy);
4409#define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits, \
4410 IsSigned, IsFP, IsBF) \
4411 if (!EltTy->isBooleanType() && \
4412 ((EltTy->hasIntegerRepresentation() && \
4413 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \
4414 (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4415 IsFP && !IsBF) || \
4416 (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4417 IsBF && !IsFP)) && \
4418 EltTySize == ElBits && NumElts == NumEls) { \
4419 return SingletonId; \
4420 }
4421#define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls) \
4422 if (EltTy->isBooleanType() && NumElts == NumEls) \
4423 return SingletonId;
4424#define SVE_OPAQUE_TYPE(Name, MangledName, Id, SingleTonId)
4425#include "clang/Basic/AArch64SVEACLETypes.def"
4426 } else if (Target->hasRISCVVTypes()) {
4427 uint64_t EltTySize = getTypeSize(EltTy);
4428#define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned, \
4429 IsFP, IsBF) \
4430 if (!EltTy->isBooleanType() && \
4431 ((EltTy->hasIntegerRepresentation() && \
4432 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \
4433 (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4434 IsFP && !IsBF) || \
4435 (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4436 IsBF && !IsFP)) && \
4437 EltTySize == ElBits && NumElts == NumEls && NumFields == NF) \
4438 return SingletonId;
4439#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4440 if (EltTy->isBooleanType() && NumElts == NumEls) \
4441 return SingletonId;
4442#include "clang/Basic/RISCVVTypes.def"
4443 }
4444 return QualType();
4445}
4446
4447/// getVectorType - Return the unique reference to a vector type of
4448/// the specified element type and size. VectorType must be a built-in type.
4450 VectorKind VecKind) const {
4451 assert(vecType->isBuiltinType() ||
4452 (vecType->isBitIntType() &&
4453 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4454 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits()) &&
4455 vecType->castAs<BitIntType>()->getNumBits() >= 8));
4456
4457 // Check if we've already instantiated a vector of this type.
4458 llvm::FoldingSetNodeID ID;
4459 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
4460
4461 void *InsertPos = nullptr;
4462 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4463 return QualType(VTP, 0);
4464
4465 // If the element type isn't canonical, this won't be a canonical type either,
4466 // so fill in the canonical type field.
4467 QualType Canonical;
4468 if (!vecType.isCanonical()) {
4469 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
4470
4471 // Get the new insert position for the node we care about.
4472 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4473 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4474 }
4475 auto *New = new (*this, alignof(VectorType))
4476 VectorType(vecType, NumElts, Canonical, VecKind);
4477 VectorTypes.InsertNode(New, InsertPos);
4478 Types.push_back(New);
4479 return QualType(New, 0);
4480}
4481
4483 SourceLocation AttrLoc,
4484 VectorKind VecKind) const {
4485 llvm::FoldingSetNodeID ID;
4486 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
4487 VecKind);
4488 void *InsertPos = nullptr;
4489 DependentVectorType *Canon =
4490 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4492
4493 if (Canon) {
4494 New = new (*this, alignof(DependentVectorType)) DependentVectorType(
4495 VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
4496 } else {
4497 QualType CanonVecTy = getCanonicalType(VecType);
4498 if (CanonVecTy == VecType) {
4499 New = new (*this, alignof(DependentVectorType))
4500 DependentVectorType(VecType, QualType(), SizeExpr, AttrLoc, VecKind);
4501
4502 DependentVectorType *CanonCheck =
4503 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4504 assert(!CanonCheck &&
4505 "Dependent-sized vector_size canonical type broken");
4506 (void)CanonCheck;
4507 DependentVectorTypes.InsertNode(New, InsertPos);
4508 } else {
4509 QualType CanonTy = getDependentVectorType(CanonVecTy, SizeExpr,
4510 SourceLocation(), VecKind);
4511 New = new (*this, alignof(DependentVectorType))
4512 DependentVectorType(VecType, CanonTy, SizeExpr, AttrLoc, VecKind);
4513 }
4514 }
4515
4516 Types.push_back(New);
4517 return QualType(New, 0);
4518}
4519
4520/// getExtVectorType - Return the unique reference to an extended vector type of
4521/// the specified element type and size. VectorType must be a built-in type.
4523 unsigned NumElts) const {
4524 assert(vecType->isBuiltinType() || vecType->isDependentType() ||
4525 (vecType->isBitIntType() &&
4526 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4527 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits()) &&
4528 vecType->castAs<BitIntType>()->getNumBits() >= 8));
4529
4530 // Check if we've already instantiated a vector of this type.
4531 llvm::FoldingSetNodeID ID;
4532 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
4534 void *InsertPos = nullptr;
4535 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4536 return QualType(VTP, 0);
4537
4538 // If the element type isn't canonical, this won't be a canonical type either,
4539 // so fill in the canonical type field.
4540 QualType Canonical;
4541 if (!vecType.isCanonical()) {
4542 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
4543
4544 // Get the new insert position for the node we care about.
4545 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4546 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4547 }
4548 auto *New = new (*this, alignof(ExtVectorType))
4549 ExtVectorType(vecType, NumElts, Canonical);
4550 VectorTypes.InsertNode(New, InsertPos);
4551 Types.push_back(New);
4552 return QualType(New, 0);
4553}
4554
4557 Expr *SizeExpr,
4558 SourceLocation AttrLoc) const {
4559 llvm::FoldingSetNodeID ID;
4561 SizeExpr);
4562
4563 void *InsertPos = nullptr;
4565 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4567 if (Canon) {
4568 // We already have a canonical version of this array type; use it as
4569 // the canonical type for a newly-built type.
4570 New = new (*this, alignof(DependentSizedExtVectorType))
4571 DependentSizedExtVectorType(vecType, QualType(Canon, 0), SizeExpr,
4572 AttrLoc);
4573 } else {
4574 QualType CanonVecTy = getCanonicalType(vecType);
4575 if (CanonVecTy == vecType) {
4576 New = new (*this, alignof(DependentSizedExtVectorType))
4577 DependentSizedExtVectorType(vecType, QualType(), SizeExpr, AttrLoc);
4578
4579 DependentSizedExtVectorType *CanonCheck
4580 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4581 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
4582 (void)CanonCheck;
4583 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
4584 } else {
4585 QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
4586 SourceLocation());
4587 New = new (*this, alignof(DependentSizedExtVectorType))
4588 DependentSizedExtVectorType(vecType, CanonExtTy, SizeExpr, AttrLoc);
4589 }
4590 }
4591
4592 Types.push_back(New);
4593 return QualType(New, 0);
4594}
4595
4597 unsigned NumColumns) const {
4598 llvm::FoldingSetNodeID ID;
4599 ConstantMatrixType::Profile(ID, ElementTy, NumRows, NumColumns,
4600 Type::ConstantMatrix);
4601
4602 assert(MatrixType::isValidElementType(ElementTy) &&
4603 "need a valid element type");
4604 assert(ConstantMatrixType::isDimensionValid(NumRows) &&
4606 "need valid matrix dimensions");
4607 void *InsertPos = nullptr;
4608 if (ConstantMatrixType *MTP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos))
4609 return QualType(MTP, 0);
4610
4611 QualType Canonical;
4612 if (!ElementTy.isCanonical()) {
4613 Canonical =
4614 getConstantMatrixType(getCanonicalType(ElementTy), NumRows, NumColumns);
4615
4616 ConstantMatrixType *NewIP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4617 assert(!NewIP && "Matrix type shouldn't already exist in the map");
4618 (void)NewIP;
4619 }
4620
4621 auto *New = new (*this, alignof(ConstantMatrixType))
4622 ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical);
4623 MatrixTypes.InsertNode(New, InsertPos);
4624 Types.push_back(New);
4625 return QualType(New, 0);
4626}
4627
4629 Expr *RowExpr,
4630 Expr *ColumnExpr,
4631 SourceLocation AttrLoc) const {
4632 QualType CanonElementTy = getCanonicalType(ElementTy);
4633 llvm::FoldingSetNodeID ID;
4634 DependentSizedMatrixType::Profile(ID, *this, CanonElementTy, RowExpr,
4635 ColumnExpr);
4636
4637 void *InsertPos = nullptr;
4639 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4640
4641 if (!Canon) {
4642 Canon = new (*this, alignof(DependentSizedMatrixType))
4643 DependentSizedMatrixType(CanonElementTy, QualType(), RowExpr,
4644 ColumnExpr, AttrLoc);
4645#ifndef NDEBUG
4646 DependentSizedMatrixType *CanonCheck =
4647 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4648 assert(!CanonCheck && "Dependent-sized matrix canonical type broken");
4649#endif
4650 DependentSizedMatrixTypes.InsertNode(Canon, InsertPos);
4651 Types.push_back(Canon);
4652 }
4653
4654 // Already have a canonical version of the matrix type
4655 //
4656 // If it exactly matches the requested type, use it directly.
4657 if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr &&
4658 Canon->getRowExpr() == ColumnExpr)
4659 return QualType(Canon, 0);
4660
4661 // Use Canon as the canonical type for newly-built type.
4662 DependentSizedMatrixType *New = new (*this, alignof(DependentSizedMatrixType))
4663 DependentSizedMatrixType(ElementTy, QualType(Canon, 0), RowExpr,
4664 ColumnExpr, AttrLoc);
4665 Types.push_back(New);
4666 return QualType(New, 0);
4667}
4668
4670 Expr *AddrSpaceExpr,
4671 SourceLocation AttrLoc) const {
4672 assert(AddrSpaceExpr->isInstantiationDependent());
4673
4674 QualType canonPointeeType = getCanonicalType(PointeeType);
4675
4676 void *insertPos = nullptr;
4677 llvm::FoldingSetNodeID ID;
4678 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
4679 AddrSpaceExpr);
4680
4681 DependentAddressSpaceType *canonTy =
4682 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
4683
4684 if (!canonTy) {
4685 canonTy = new (*this, alignof(DependentAddressSpaceType))
4686 DependentAddressSpaceType(canonPointeeType, QualType(), AddrSpaceExpr,
4687 AttrLoc);
4688 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
4689 Types.push_back(canonTy);
4690 }
4691
4692 if (canonPointeeType == PointeeType &&
4693 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
4694 return QualType(canonTy, 0);
4695
4696 auto *sugaredType = new (*this, alignof(DependentAddressSpaceType))
4697 DependentAddressSpaceType(PointeeType, QualType(canonTy, 0),
4698 AddrSpaceExpr, AttrLoc);
4699 Types.push_back(sugaredType);
4700 return QualType(sugaredType, 0);
4701}
4702
4703/// Determine whether \p T is canonical as the result type of a function.
4705 return T.isCanonical() &&
4706 (T.getObjCLifetime() == Qualifiers::OCL_None ||
4707 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
4708}
4709
4710/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
4713 const FunctionType::ExtInfo &Info) const {
4714 // FIXME: This assertion cannot be enabled (yet) because the ObjC rewriter
4715 // functionality creates a function without a prototype regardless of
4716 // language mode (so it makes them even in C++). Once the rewriter has been
4717 // fixed, this assertion can be enabled again.
4718 //assert(!LangOpts.requiresStrictPrototypes() &&
4719 // "strict prototypes are disabled");
4720
4721 // Unique functions, to guarantee there is only one function of a particular
4722 // structure.
4723 llvm::FoldingSetNodeID ID;
4724 FunctionNoProtoType::Profile(ID, ResultTy, Info);
4725
4726 void *InsertPos = nullptr;
4727 if (FunctionNoProtoType *FT =
4728 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
4729 return QualType(FT, 0);
4730
4731 QualType Canonical;
4732 if (!isCanonicalResultType(ResultTy)) {
4733 Canonical =
4735
4736 // Get the new insert position for the node we care about.
4737 FunctionNoProtoType *NewIP =
4738 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
4739 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4740 }
4741
4742 auto *New = new (*this, alignof(FunctionNoProtoType))
4743 FunctionNoProtoType(ResultTy, Canonical, Info);
4744 Types.push_back(New);
4745 FunctionNoProtoTypes.InsertNode(New, InsertPos);
4746 return QualType(New, 0);
4747}
4748
4751 CanQualType CanResultType = getCanonicalType(ResultType);
4752
4753 // Canonical result types do not have ARC lifetime qualifiers.
4754 if (CanResultType.getQualifiers().hasObjCLifetime()) {
4755 Qualifiers Qs = CanResultType.getQualifiers();
4756 Qs.removeObjCLifetime();
4758 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
4759 }
4760
4761 return CanResultType;
4762}
4763
4765 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
4766 if (ESI.Type == EST_None)
4767 return true;
4768 if (!NoexceptInType)
4769 return false;
4770
4771 // C++17 onwards: exception specification is part of the type, as a simple
4772 // boolean "can this function type throw".
4773 if (ESI.Type == EST_BasicNoexcept)
4774 return true;
4775
4776 // A noexcept(expr) specification is (possibly) canonical if expr is
4777 // value-dependent.
4778 if (ESI.Type == EST_DependentNoexcept)
4779 return true;
4780
4781 // A dynamic exception specification is canonical if it only contains pack
4782 // expansions (so we can't tell whether it's non-throwing) and all its
4783 // contained types are canonical.
4784 if (ESI.Type == EST_Dynamic) {
4785 bool AnyPackExpansions = false;
4786 for (QualType ET : ESI.Exceptions) {
4787 if (!ET.isCanonical())
4788 return false;
4789 if (ET->getAs<PackExpansionType>())
4790 AnyPackExpansions = true;
4791 }
4792 return AnyPackExpansions;
4793 }
4794
4795 return false;
4796}
4797
4798QualType ASTContext::getFunctionTypeInternal(
4799 QualType ResultTy, ArrayRef<QualType> ArgArray,
4800 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
4801 size_t NumArgs = ArgArray.size();
4802
4803 // Unique functions, to guarantee there is only one function of a particular
4804 // structure.
4805 llvm::FoldingSetNodeID ID;
4806 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
4807 *this, true);
4808
4809 QualType Canonical;
4810 bool Unique = false;
4811
4812 void *InsertPos = nullptr;
4813 if (FunctionProtoType *FPT =
4814 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
4815 QualType Existing = QualType(FPT, 0);
4816
4817 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
4818 // it so long as our exception specification doesn't contain a dependent
4819 // noexcept expression, or we're just looking for a canonical type.
4820 // Otherwise, we're going to need to create a type
4821 // sugar node to hold the concrete expression.
4822 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
4823 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
4824 return Existing;
4825
4826 // We need a new type sugar node for this one, to hold the new noexcept
4827 // expression. We do no canonicalization here, but that's OK since we don't
4828 // expect to see the same noexcept expression much more than once.
4829 Canonical = getCanonicalType(Existing);
4830 Unique = true;
4831 }
4832
4833 bool NoexceptInType = getLangOpts().CPlusPlus17;
4834 bool IsCanonicalExceptionSpec =
4836
4837 // Determine whether the type being created is already canonical or not.
4838 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
4839 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
4840 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
4841 if (!ArgArray[i].isCanonicalAsParam())
4842 isCanonical = false;
4843
4844 if (OnlyWantCanonical)
4845 assert(isCanonical &&
4846 "given non-canonical parameters constructing canonical type");
4847
4848 // If this type isn't canonical, get the canonical version of it if we don't
4849 // already have it. The exception spec is only partially part of the
4850 // canonical type, and only in C++17 onwards.
4851 if (!isCanonical && Canonical.isNull()) {
4852 SmallVector<QualType, 16> CanonicalArgs;
4853 CanonicalArgs.reserve(NumArgs);
4854 for (unsigned i = 0; i != NumArgs; ++i)
4855 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
4856
4857 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
4858 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
4859 CanonicalEPI.HasTrailingReturn = false;
4860
4861 if (IsCanonicalExceptionSpec) {
4862 // Exception spec is already OK.
4863 } else if (NoexceptInType) {
4864 switch (EPI.ExceptionSpec.Type) {
4866 // We don't know yet. It shouldn't matter what we pick here; no-one
4867 // should ever look at this.
4868 [[fallthrough]];
4869 case EST_None: case EST_MSAny: case EST_NoexceptFalse:
4870 CanonicalEPI.ExceptionSpec.Type = EST_None;
4871 break;
4872
4873 // A dynamic exception specification is almost always "not noexcept",
4874 // with the exception that a pack expansion might expand to no types.
4875 case EST_Dynamic: {
4876 bool AnyPacks = false;
4877 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
4878 if (ET->getAs<PackExpansionType>())
4879 AnyPacks = true;
4880 ExceptionTypeStorage.push_back(getCanonicalType(ET));
4881 }
4882 if (!AnyPacks)
4883 CanonicalEPI.ExceptionSpec.Type = EST_None;
4884 else {
4885 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
4886 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
4887 }
4888 break;
4889 }
4890
4891 case EST_DynamicNone:
4892 case EST_BasicNoexcept:
4893 case EST_NoexceptTrue:
4894 case EST_NoThrow:
4895 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
4896 break;
4897
4899 llvm_unreachable("dependent noexcept is already canonical");
4900 }
4901 } else {
4903 }
4904
4905 // Adjust the canonical function result type.
4906 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
4907 Canonical =
4908 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
4909
4910 // Get the new insert position for the node we care about.
4911 FunctionProtoType *NewIP =
4912 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
4913 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4914 }
4915
4916 // Compute the needed size to hold this FunctionProtoType and the
4917 // various trailing objects.
4918 auto ESH = FunctionProtoType::getExceptionSpecSize(
4919 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
4920 size_t Size = FunctionProtoType::totalSizeToAlloc<
4926 EPI.requiresFunctionProtoTypeArmAttributes(), ESH.NumExceptionType,
4927 ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
4928 EPI.ExtParameterInfos ? NumArgs : 0,
4930 EPI.FunctionEffects.conditions().size());
4931
4932 auto *FTP = (FunctionProtoType *)Allocate(Size, alignof(FunctionProtoType));
4934 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
4935 Types.push_back(FTP);
4936 if (!Unique)
4937 FunctionProtoTypes.InsertNode(FTP, InsertPos);
4938 if (!EPI.FunctionEffects.empty())
4939 AnyFunctionEffects = true;
4940 return QualType(FTP, 0);
4941}
4942
4943QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
4944 llvm::FoldingSetNodeID ID;
4945 PipeType::Profile(ID, T, ReadOnly);
4946
4947 void *InsertPos = nullptr;
4948 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
4949 return QualType(PT, 0);
4950
4951 // If the pipe element type isn't canonical, this won't be a canonical type
4952 // either, so fill in the canonical type field.
4953 QualType Canonical;
4954 if (!T.isCanonical()) {
4955 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
4956
4957 // Get the new insert position for the node we care about.
4958 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
4959 assert(!NewIP && "Shouldn't be in the map!");
4960 (void)NewIP;
4961 }
4962 auto *New = new (*this, alignof(PipeType)) PipeType(T, Canonical, ReadOnly);
4963 Types.push_back(New);
4964 PipeTypes.InsertNode(New, InsertPos);
4965 return QualType(New, 0);
4966}
4967
4969 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
4970 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
4971 : Ty;
4972}
4973
4975 return getPipeType(T, true);
4976}
4977
4979 return getPipeType(T, false);
4980}
4981
4982QualType ASTContext::getBitIntType(bool IsUnsigned, unsigned NumBits) const {
4983 llvm::FoldingSetNodeID ID;
4984 BitIntType::Profile(ID, IsUnsigned, NumBits);
4985
4986 void *InsertPos = nullptr;
4987 if (BitIntType *EIT = BitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
4988 return QualType(EIT, 0);
4989
4990 auto *New = new (*this, alignof(BitIntType)) BitIntType(IsUnsigned, NumBits);
4991 BitIntTypes.InsertNode(New, InsertPos);
4992 Types.push_back(New);
4993 return QualType(New, 0);
4994}
4995
4997 Expr *NumBitsExpr) const {
4998 assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent");
4999 llvm::FoldingSetNodeID ID;
5000 DependentBitIntType::Profile(ID, *this, IsUnsigned, NumBitsExpr);
5001
5002 void *InsertPos = nullptr;
5003 if (DependentBitIntType *Existing =
5004 DependentBitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
5005 return QualType(Existing, 0);
5006
5007 auto *New = new (*this, alignof(DependentBitIntType))
5008 DependentBitIntType(IsUnsigned, NumBitsExpr);
5009 DependentBitIntTypes.InsertNode(New, InsertPos);
5010
5011 Types.push_back(New);
5012 return QualType(New, 0);
5013}
5014
5015#ifndef NDEBUG
5017 if (!isa<CXXRecordDecl>(D)) return false;
5018 const auto *RD = cast<CXXRecordDecl>(D);
5019 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
5020 return true;
5021 if (RD->getDescribedClassTemplate() &&
5022 !isa<ClassTemplateSpecializationDecl>(RD))
5023 return true;
5024 return false;
5025}
5026#endif
5027
5028/// getInjectedClassNameType - Return the unique reference to the
5029/// injected class name type for the specified templated declaration.
5031 QualType TST) const {
5033 if (Decl->TypeForDecl) {
5034 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
5035 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
5036 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
5037 Decl->TypeForDecl = PrevDecl->TypeForDecl;
5038 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
5039 } else {
5040 Type *newType = new (*this, alignof(InjectedClassNameType))
5042 Decl->TypeForDecl = newType;
5043 Types.push_back(newType);
5044 }
5045 return QualType(Decl->TypeForDecl, 0);
5046}
5047
5048/// getTypeDeclType - Return the unique reference to the type for the
5049/// specified type declaration.
5050QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
5051 assert(Decl && "Passed null for Decl param");
5052 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
5053
5054 if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
5055 return getTypedefType(Typedef);
5056
5057 assert(!isa<TemplateTypeParmDecl>(Decl) &&
5058 "Template type parameter types are always available.");
5059
5060 if (const auto *Record = dyn_cast<RecordDecl>(Decl)) {
5061 assert(Record->isFirstDecl() && "struct/union has previous declaration");
5063 return getRecordType(Record);
5064 } else if (const auto *Enum = dyn_cast<EnumDecl>(Decl)) {
5065 assert(Enum->isFirstDecl() && "enum has previous declaration");
5066 return getEnumType(Enum);
5067 } else if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
5068 return getUnresolvedUsingType(Using);
5069 } else
5070 llvm_unreachable("TypeDecl without a type?");
5071
5072 return QualType(Decl->TypeForDecl, 0);
5073}
5074
5075/// getTypedefType - Return the unique reference to the type for the
5076/// specified typedef name decl.
5078 QualType Underlying) const {
5079 if (!Decl->TypeForDecl) {
5080 if (Underlying.isNull())
5081 Underlying = Decl->getUnderlyingType();
5082 auto *NewType = new (*this, alignof(TypedefType)) TypedefType(
5083 Type::Typedef, Decl, QualType(), getCanonicalType(Underlying));
5084 Decl->TypeForDecl = NewType;
5085 Types.push_back(NewType);
5086 return QualType(NewType, 0);
5087 }
5088 if (Underlying.isNull() || Decl->getUnderlyingType() == Underlying)
5089 return QualType(Decl->TypeForDecl, 0);
5090 assert(hasSameType(Decl->getUnderlyingType(), Underlying));
5091
5092 llvm::FoldingSetNodeID ID;
5093 TypedefType::Profile(ID, Decl, Underlying);
5094
5095 void *InsertPos = nullptr;
5096 if (TypedefType *T = TypedefTypes.FindNodeOrInsertPos(ID, InsertPos)) {
5097 assert(!T->typeMatchesDecl() &&
5098 "non-divergent case should be handled with TypeDecl");
5099 return QualType(T, 0);
5100 }
5101
5102 void *Mem = Allocate(TypedefType::totalSizeToAlloc<QualType>(true),
5103 alignof(TypedefType));
5104 auto *NewType = new (Mem) TypedefType(Type::Typedef, Decl, Underlying,
5105 getCanonicalType(Underlying));
5106 TypedefTypes.InsertNode(NewType, InsertPos);
5107 Types.push_back(NewType);
5108 return QualType(NewType, 0);
5109}
5110
5112 QualType Underlying) const {
5113 llvm::FoldingSetNodeID ID;
5114 UsingType::Profile(ID, Found, Underlying);
5115
5116 void *InsertPos = nullptr;
5117 if (UsingType *T = UsingTypes.FindNodeOrInsertPos(ID, InsertPos))
5118 return QualType(T, 0);
5119
5120 const Type *TypeForDecl =
5121 cast<TypeDecl>(Found->getTargetDecl())->getTypeForDecl();
5122
5123 assert(!Underlying.hasLocalQualifiers());
5124 QualType Canon = Underlying->getCanonicalTypeInternal();
5125 assert(TypeForDecl->getCanonicalTypeInternal() == Canon);
5126
5127 if (Underlying.getTypePtr() == TypeForDecl)
5128 Underlying = QualType();
5129 void *Mem =
5130 Allocate(UsingType::totalSizeToAlloc<QualType>(!Underlying.isNull()),
5131 alignof(UsingType));
5132 UsingType *NewType = new (Mem) UsingType(Found, Underlying, Canon);
5133 Types.push_back(NewType);
5134 UsingTypes.InsertNode(NewType, InsertPos);
5135 return QualType(NewType, 0);
5136}
5137
5139 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
5140
5141 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
5142 if (PrevDecl->TypeForDecl)
5143 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
5144
5145 auto *newType = new (*this, alignof(RecordType)) RecordType(Decl);
5146 Decl->TypeForDecl = newType;
5147 Types.push_back(newType);
5148 return QualType(newType, 0);
5149}
5150
5152 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
5153
5154 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
5155 if (PrevDecl->TypeForDecl)
5156 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
5157
5158 auto *newType = new (*this, alignof(EnumType)) EnumType(Decl);
5159 Decl->TypeForDecl = newType;
5160 Types.push_back(newType);
5161 return QualType(newType, 0);
5162}
5163
5165 const UnresolvedUsingTypenameDecl *Decl) const {
5166 if (Decl->TypeForDecl)
5167 return QualType(Decl->TypeForDecl, 0);
5168
5169 if (const UnresolvedUsingTypenameDecl *CanonicalDecl =
5171 if (CanonicalDecl->TypeForDecl)
5172 return QualType(Decl->TypeForDecl = CanonicalDecl->TypeForDecl, 0);
5173
5174 Type *newType =
5175 new (*this, alignof(UnresolvedUsingType)) UnresolvedUsingType(Decl);
5176 Decl->TypeForDecl = newType;
5177 Types.push_back(newType);
5178 return QualType(newType, 0);
5179}
5180
5182 QualType modifiedType,
5183 QualType equivalentType) const {
5184 llvm::FoldingSetNodeID id;
5185 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
5186
5187 void *insertPos = nullptr;
5188 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
5189 if (type) return QualType(type, 0);
5190
5191 QualType canon = getCanonicalType(equivalentType);
5192 type = new (*this, alignof(AttributedType))
5193 AttributedType(canon, attrKind, modifiedType, equivalentType);
5194
5195 Types.push_back(type);
5196 AttributedTypes.InsertNode(type, insertPos);
5197
5198 return QualType(type, 0);
5199}
5200
5201QualType ASTContext::getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
5202 QualType Wrapped) {
5203 llvm::FoldingSetNodeID ID;
5204 BTFTagAttributedType::Profile(ID, Wrapped, BTFAttr);
5205
5206 void *InsertPos = nullptr;
5208 BTFTagAttributedTypes.FindNodeOrInsertPos(ID, InsertPos);
5209 if (Ty)
5210 return QualType(Ty, 0);
5211
5212 QualType Canon = getCanonicalType(Wrapped);
5213 Ty = new (*this, alignof(BTFTagAttributedType))
5214 BTFTagAttributedType(Canon, Wrapped, BTFAttr);
5215
5216 Types.push_back(Ty);
5217 BTFTagAttributedTypes.InsertNode(Ty, InsertPos);
5218
5219 return QualType(Ty, 0);
5220}
5221
5222/// Retrieve a substitution-result type.
5224 QualType Replacement, Decl *AssociatedDecl, unsigned Index,
5225 std::optional<unsigned> PackIndex) const {
5226 llvm::FoldingSetNodeID ID;
5227 SubstTemplateTypeParmType::Profile(ID, Replacement, AssociatedDecl, Index,
5228 PackIndex);
5229 void *InsertPos = nullptr;
5230 SubstTemplateTypeParmType *SubstParm =
5231 SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
5232
5233 if (!SubstParm) {
5234 void *Mem = Allocate(SubstTemplateTypeParmType::totalSizeToAlloc<QualType>(
5235 !Replacement.isCanonical()),
5236 alignof(SubstTemplateTypeParmType));
5237 SubstParm = new (Mem) SubstTemplateTypeParmType(Replacement, AssociatedDecl,
5238 Index, PackIndex);
5239 Types.push_back(SubstParm);
5240 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
5241 }
5242
5243 return QualType(SubstParm, 0);
5244}
5245
5246/// Retrieve a
5249 unsigned Index, bool Final,
5250 const TemplateArgument &ArgPack) {
5251#ifndef NDEBUG
5252 for (const auto &P : ArgPack.pack_elements())
5253 assert(P.getKind() == TemplateArgument::Type && "Pack contains a non-type");
5254#endif
5255
5256 llvm::FoldingSetNodeID ID;
5257 SubstTemplateTypeParmPackType::Profile(ID, AssociatedDecl, Index, Final,
5258 ArgPack);
5259 void *InsertPos = nullptr;
5260 if (SubstTemplateTypeParmPackType *SubstParm =
5261 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
5262 return QualType(SubstParm, 0);
5263
5264 QualType Canon;
5265 {
5266 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(ArgPack);
5267 if (!AssociatedDecl->isCanonicalDecl() ||
5268 !CanonArgPack.structurallyEquals(ArgPack)) {
5270 AssociatedDecl->getCanonicalDecl(), Index, Final, CanonArgPack);
5271 [[maybe_unused]] const auto *Nothing =
5272 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
5273 assert(!Nothing);
5274 }
5275 }
5276
5277 auto *SubstParm = new (*this, alignof(SubstTemplateTypeParmPackType))
5278 SubstTemplateTypeParmPackType(Canon, AssociatedDecl, Index, Final,
5279 ArgPack);
5280 Types.push_back(SubstParm);
5281 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
5282 return QualType(SubstParm, 0);
5283}
5284
5285/// Retrieve the template type parameter type for a template
5286/// parameter or parameter pack with the given depth, index, and (optionally)
5287/// name.
5288QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
5289 bool ParameterPack,
5290 TemplateTypeParmDecl *TTPDecl) const {
5291 llvm::FoldingSetNodeID ID;
5292 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
5293 void *InsertPos = nullptr;
5294 TemplateTypeParmType *TypeParm
5295 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
5296
5297 if (TypeParm)
5298 return QualType(TypeParm, 0);
5299
5300 if (TTPDecl) {
5301 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
5302 TypeParm = new (*this, alignof(TemplateTypeParmType))
5303 TemplateTypeParmType(Depth, Index, ParameterPack, TTPDecl, Canon);
5304
5305 TemplateTypeParmType *TypeCheck
5306 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
5307 assert(!TypeCheck && "Template type parameter canonical type broken");
5308 (void)TypeCheck;
5309 } else
5310 TypeParm = new (*this, alignof(TemplateTypeParmType)) TemplateTypeParmType(
5311 Depth, Index, ParameterPack, /*TTPDecl=*/nullptr, /*Canon=*/QualType());
5312
5313 Types.push_back(TypeParm);
5314 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
5315
5316 return QualType(TypeParm, 0);
5317}
5318
5321 SourceLocation NameLoc,
5322 const TemplateArgumentListInfo &Args,
5323 QualType Underlying) const {
5324 assert(!Name.getAsDependentTemplateName() &&
5325 "No dependent template names here!");
5326 QualType TST =
5327 getTemplateSpecializationType(Name, Args.arguments(), Underlying);
5328
5333 TL.setTemplateNameLoc(NameLoc);
5334 TL.setLAngleLoc(Args.getLAngleLoc());
5335 TL.setRAngleLoc(Args.getRAngleLoc());
5336 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5337 TL.setArgLocInfo(i, Args[i].getLocInfo());
5338 return DI;
5339}
5340
5344 QualType Underlying) const {
5345 assert(!Template.getAsDependentTemplateName() &&
5346 "No dependent template names here!");
5347
5349 ArgVec.reserve(Args.size());
5350 for (const TemplateArgumentLoc &Arg : Args)
5351 ArgVec.push_back(Arg.getArgument());
5352
5353 return getTemplateSpecializationType(Template, ArgVec, Underlying);
5354}
5355
5356#ifndef NDEBUG
5358 for (const TemplateArgument &Arg : Args)
5359 if (Arg.isPackExpansion())
5360 return true;
5361
5362 return true;
5363}
5364#endif
5365
5369 QualType Underlying) const {
5370 assert(!Template.getAsDependentTemplateName() &&
5371 "No dependent template names here!");
5372
5373 const auto *TD = Template.getAsTemplateDecl();
5374 bool IsTypeAlias = TD && TD->isTypeAlias();
5375 QualType CanonType;
5376 if (!Underlying.isNull())
5377 CanonType = getCanonicalType(Underlying);
5378 else {
5379 // We can get here with an alias template when the specialization contains
5380 // a pack expansion that does not match up with a parameter pack.
5381 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
5382 "Caller must compute aliased type");
5383 IsTypeAlias = false;
5384 CanonType = getCanonicalTemplateSpecializationType(Template, Args);
5385 }
5386
5387 // Allocate the (non-canonical) template specialization type, but don't
5388 // try to unique it: these types typically have location information that
5389 // we don't unique and don't want to lose.
5390 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
5391 sizeof(TemplateArgument) * Args.size() +
5392 (IsTypeAlias ? sizeof(QualType) : 0),
5394 auto *Spec
5395 = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
5396 IsTypeAlias ? Underlying : QualType());
5397
5398 Types.push_back(Spec);
5399 return QualType(Spec, 0);
5400}
5401
5403 TemplateName Template, ArrayRef<TemplateArgument> Args) const {
5404 assert(!Template.getAsDependentTemplateName() &&
5405 "No dependent template names here!");
5406
5407 // Build the canonical template specialization type.
5408 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
5409 bool AnyNonCanonArgs = false;
5410 auto CanonArgs =
5411 ::getCanonicalTemplateArguments(*this, Args, AnyNonCanonArgs);
5412
5413 // Determine whether this canonical template specialization type already
5414 // exists.
5415 llvm::FoldingSetNodeID ID;
5416 TemplateSpecializationType::Profile(ID, CanonTemplate,
5417 CanonArgs, *this);
5418
5419 void *InsertPos = nullptr;
5421 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
5422
5423 if (!Spec) {
5424 // Allocate a new canonical template specialization type.
5425 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
5426 sizeof(TemplateArgument) * CanonArgs.size()),
5428 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
5429 CanonArgs,
5430 QualType(), QualType());
5431 Types.push_back(Spec);
5432 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
5433 }
5434
5435 assert(Spec->isDependentType() &&
5436 "Non-dependent template-id type must have a canonical type");
5437 return QualType(Spec, 0);
5438}
5439
5442 QualType NamedType,
5443 TagDecl *OwnedTagDecl) const {
5444 llvm::FoldingSetNodeID ID;
5445 ElaboratedType::Profile(ID, Keyword, NNS, NamedType, OwnedTagDecl);
5446
5447 void *InsertPos = nullptr;
5448 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
5449 if (T)
5450 return QualType(T, 0);
5451
5452 QualType Canon = NamedType;
5453 if (!Canon.isCanonical()) {
5454 Canon = getCanonicalType(NamedType);
5455 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
5456 assert(!CheckT && "Elaborated canonical type broken");
5457 (void)CheckT;
5458 }
5459
5460 void *Mem =
5461 Allocate(ElaboratedType::totalSizeToAlloc<TagDecl *>(!!OwnedTagDecl),
5462 alignof(ElaboratedType));
5463 T = new (Mem) ElaboratedType(Keyword, NNS, NamedType, Canon, OwnedTagDecl);
5464
5465 Types.push_back(T);
5466 ElaboratedTypes.InsertNode(T, InsertPos);
5467 return QualType(T, 0);
5468}
5469
5472 llvm::FoldingSetNodeID ID;
5473 ParenType::Profile(ID, InnerType);
5474
5475 void *InsertPos = nullptr;
5476 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
5477 if (T)
5478 return QualType(T, 0);
5479
5480 QualType Canon = InnerType;
5481 if (!Canon.isCanonical()) {
5482 Canon = getCanonicalType(InnerType);
5483 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
5484 assert(!CheckT && "Paren canonical type broken");
5485 (void)CheckT;
5486 }
5487
5488 T = new (*this, alignof(ParenType)) ParenType(InnerType, Canon);
5489 Types.push_back(T);
5490 ParenTypes.InsertNode(T, InsertPos);
5491 return QualType(T, 0);
5492}
5493
5496 const IdentifierInfo *MacroII) const {
5497 QualType Canon = UnderlyingTy;
5498 if (!Canon.isCanonical())
5499 Canon = getCanonicalType(UnderlyingTy);
5500
5501 auto *newType = new (*this, alignof(MacroQualifiedType))
5502 MacroQualifiedType(UnderlyingTy, Canon, MacroII);
5503 Types.push_back(newType);
5504 return QualType(newType, 0);
5505}
5506
5509 const IdentifierInfo *Name,
5510 QualType Canon) const {
5511 if (Canon.isNull()) {
5513 if (CanonNNS != NNS)
5514 Canon = getDependentNameType(Keyword, CanonNNS, Name);
5515 }
5516
5517 llvm::FoldingSetNodeID ID;
5518 DependentNameType::Profile(ID, Keyword, NNS, Name);
5519
5520 void *InsertPos = nullptr;
5522 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
5523 if (T)
5524 return QualType(T, 0);
5525
5526 T = new (*this, alignof(DependentNameType))
5527 DependentNameType(Keyword, NNS, Name, Canon);
5528 Types.push_back(T);
5529 DependentNameTypes.InsertNode(T, InsertPos);
5530 return QualType(T, 0);
5531}
5532
5535 const IdentifierInfo *Name, ArrayRef<TemplateArgumentLoc> Args) const {
5536 // TODO: avoid this copy
5538 for (unsigned I = 0, E = Args.size(); I != E; ++I)
5539 ArgCopy.push_back(Args[I].getArgument());
5540 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
5541}
5542
5545 ElaboratedTypeKeyword Keyword,
5547 const IdentifierInfo *Name,
5548 ArrayRef<TemplateArgument> Args) const {
5549 assert((!NNS || NNS->isDependent()) &&
5550 "nested-name-specifier must be dependent");
5551
5552 llvm::FoldingSetNodeID ID;
5553 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
5554 Name, Args);
5555
5556 void *InsertPos = nullptr;
5558 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
5559 if (T)
5560 return QualType(T, 0);
5561
5563
5564 ElaboratedTypeKeyword CanonKeyword = Keyword;
5565 if (Keyword == ElaboratedTypeKeyword::None)
5566 CanonKeyword = ElaboratedTypeKeyword::Typename;
5567
5568 bool AnyNonCanonArgs = false;
5569 auto CanonArgs =
5570 ::getCanonicalTemplateArguments(*this, Args, AnyNonCanonArgs);
5571
5572 QualType Canon;
5573 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
5574 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
5575 Name,
5576 CanonArgs);
5577
5578 // Find the insert position again.
5579 [[maybe_unused]] auto *Nothing =
5580 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
5581 assert(!Nothing && "canonical type broken");
5582 }
5583
5584 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
5585 sizeof(TemplateArgument) * Args.size()),
5587 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
5588 Name, Args, Canon);
5589 Types.push_back(T);
5590 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
5591 return QualType(T, 0);
5592}
5593
5595 TemplateArgument Arg;
5596 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
5597 QualType ArgType = getTypeDeclType(TTP);
5598 if (TTP->isParameterPack())
5599 ArgType = getPackExpansionType(ArgType, std::nullopt);
5600
5601 Arg = TemplateArgument(ArgType);
5602 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5603 QualType T =
5604 NTTP->getType().getNonPackExpansionType().getNonLValueExprType(*this);
5605 // For class NTTPs, ensure we include the 'const' so the type matches that
5606 // of a real template argument.
5607 // FIXME: It would be more faithful to model this as something like an
5608 // lvalue-to-rvalue conversion applied to a const-qualified lvalue.
5609 ExprValueKind VK;
5610 if (T->isRecordType()) {
5611 // C++ [temp.param]p8: An id-expression naming a non-type
5612 // template-parameter of class type T denotes a static storage duration
5613 // object of type const T.
5614 T.addConst();
5615 VK = VK_LValue;
5616 } else {
5617 VK = Expr::getValueKindForType(NTTP->getType());
5618 }
5619 Expr *E = new (*this)
5620 DeclRefExpr(*this, NTTP, /*RefersToEnclosingVariableOrCapture=*/false,
5621 T, VK, NTTP->getLocation());
5622
5623 if (NTTP->isParameterPack())
5624 E = new (*this)
5625 PackExpansionExpr(DependentTy, E, NTTP->getLocation(), std::nullopt);
5626 Arg = TemplateArgument(E);
5627 } else {
5628 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
5630 nullptr, /*TemplateKeyword=*/false, TemplateName(TTP));
5631 if (TTP->isParameterPack())
5632 Arg = TemplateArgument(Name, std::optional<unsigned>());
5633 else
5634 Arg = TemplateArgument(Name);
5635 }
5636
5637 if (Param->isTemplateParameterPack())
5638 Arg = TemplateArgument::CreatePackCopy(*this, Arg);
5639
5640 return Arg;
5641}
5642
5643void
5646 Args.reserve(Args.size() + Params->size());
5647
5648 for (NamedDecl *Param : *Params)
5649 Args.push_back(getInjectedTemplateArg(Param));
5650}
5651
5653 std::optional<unsigned> NumExpansions,
5654 bool ExpectPackInType) {
5655 assert((!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) &&
5656 "Pack expansions must expand one or more parameter packs");
5657
5658 llvm::FoldingSetNodeID ID;
5659 PackExpansionType::Profile(ID, Pattern, NumExpansions);
5660
5661 void *InsertPos = nullptr;
5662 PackExpansionType *T = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
5663 if (T)
5664 return QualType(T, 0);
5665
5666 QualType Canon;
5667 if (!Pattern.isCanonical()) {
5668 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions,
5669 /*ExpectPackInType=*/false);
5670
5671 // Find the insert position again, in case we inserted an element into
5672 // PackExpansionTypes and invalidated our insert position.
5673 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
5674 }
5675
5676 T = new (*this, alignof(PackExpansionType))
5677 PackExpansionType(Pattern, Canon, NumExpansions);
5678 Types.push_back(T);
5679 PackExpansionTypes.InsertNode(T, InsertPos);
5680 return QualType(T, 0);
5681}
5682
5683/// CmpProtocolNames - Comparison predicate for sorting protocols
5684/// alphabetically.
5685static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
5686 ObjCProtocolDecl *const *RHS) {
5687 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
5688}
5689
5691 if (Protocols.empty()) return true;
5692
5693 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
5694 return false;
5695
5696 for (unsigned i = 1; i != Protocols.size(); ++i)
5697 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
5698 Protocols[i]->getCanonicalDecl() != Protocols[i])
5699 return false;
5700 return true;
5701}
5702
5703static void
5705 // Sort protocols, keyed by name.
5706 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
5707
5708 // Canonicalize.
5709 for (ObjCProtocolDecl *&P : Protocols)
5710 P = P->getCanonicalDecl();
5711
5712 // Remove duplicates.
5713 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
5714 Protocols.erase(ProtocolsEnd, Protocols.end());
5715}
5716
5718 ObjCProtocolDecl * const *Protocols,
5719 unsigned NumProtocols) const {
5720 return getObjCObjectType(BaseType, {},
5721 llvm::ArrayRef(Protocols, NumProtocols),
5722 /*isKindOf=*/false);
5723}
5724
5726 QualType baseType,
5727 ArrayRef<QualType> typeArgs,
5729 bool isKindOf) const {
5730 // If the base type is an interface and there aren't any protocols or
5731 // type arguments to add, then the interface type will do just fine.
5732 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
5733 isa<ObjCInterfaceType>(baseType))
5734 return baseType;
5735
5736 // Look in the folding set for an existing type.
5737 llvm::FoldingSetNodeID ID;
5738 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
5739 void *InsertPos = nullptr;
5740 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
5741 return QualType(QT, 0);
5742
5743 // Determine the type arguments to be used for canonicalization,
5744 // which may be explicitly specified here or written on the base
5745 // type.
5746 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
5747 if (effectiveTypeArgs.empty()) {
5748 if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
5749 effectiveTypeArgs = baseObject->getTypeArgs();
5750 }
5751
5752 // Build the canonical type, which has the canonical base type and a
5753 // sorted-and-uniqued list of protocols and the type arguments
5754 // canonicalized.
5755 QualType canonical;
5756 bool typeArgsAreCanonical = llvm::all_of(
5757 effectiveTypeArgs, [&](QualType type) { return type.isCanonical(); });
5758 bool protocolsSorted = areSortedAndUniqued(protocols);
5759 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
5760 // Determine the canonical type arguments.
5761 ArrayRef<QualType> canonTypeArgs;
5762 SmallVector<QualType, 4> canonTypeArgsVec;
5763 if (!typeArgsAreCanonical) {
5764 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
5765 for (auto typeArg : effectiveTypeArgs)
5766 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
5767 canonTypeArgs = canonTypeArgsVec;
5768 } else {
5769 canonTypeArgs = effectiveTypeArgs;
5770 }
5771
5772 ArrayRef<ObjCProtocolDecl *> canonProtocols;
5773 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
5774 if (!protocolsSorted) {
5775 canonProtocolsVec.append(protocols.begin(), protocols.end());
5776 SortAndUniqueProtocols(canonProtocolsVec);
5777 canonProtocols = canonProtocolsVec;
5778 } else {
5779 canonProtocols = protocols;
5780 }
5781
5782 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
5783 canonProtocols, isKindOf);
5784
5785 // Regenerate InsertPos.
5786 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
5787 }
5788
5789 unsigned size = sizeof(ObjCObjectTypeImpl);
5790 size += typeArgs.size() * sizeof(QualType);
5791 size += protocols.size() * sizeof(ObjCProtocolDecl *);
5792 void *mem = Allocate(size, alignof(ObjCObjectTypeImpl));
5793 auto *T =
5794 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
5795 isKindOf);
5796
5797 Types.push_back(T);
5798 ObjCObjectTypes.InsertNode(T, InsertPos);
5799 return QualType(T, 0);
5800}
5801
5802/// Apply Objective-C protocol qualifiers to the given type.
5803/// If this is for the canonical type of a type parameter, we can apply
5804/// protocol qualifiers on the ObjCObjectPointerType.
5807 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
5808 bool allowOnPointerType) const {
5809 hasError = false;
5810
5811 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
5812 return getObjCTypeParamType(objT->getDecl(), protocols);
5813 }
5814
5815 // Apply protocol qualifiers to ObjCObjectPointerType.
5816 if (allowOnPointerType) {
5817 if (const auto *objPtr =
5818 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
5819 const ObjCObjectType *objT = objPtr->getObjectType();
5820 // Merge protocol lists and construct ObjCObjectType.
5822 protocolsVec.append(objT->qual_begin(),
5823 objT->qual_end());
5824 protocolsVec.append(protocols.begin(), protocols.end());
5825 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
5827 objT->getBaseType(),
5828 objT->getTypeArgsAsWritten(),
5829 protocols,
5830 objT->isKindOfTypeAsWritten());
5832 }
5833 }
5834
5835 // Apply protocol qualifiers to ObjCObjectType.
5836 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
5837 // FIXME: Check for protocols to which the class type is already
5838 // known to conform.
5839
5840 return getObjCObjectType(objT->getBaseType(),
5841 objT->getTypeArgsAsWritten(),
5842 protocols,
5843 objT->isKindOfTypeAsWritten());
5844 }
5845
5846 // If the canonical type is ObjCObjectType, ...
5847 if (type->isObjCObjectType()) {
5848 // Silently overwrite any existing protocol qualifiers.
5849 // TODO: determine whether that's the right thing to do.
5850
5851 // FIXME: Check for protocols to which the class type is already
5852 // known to conform.
5853 return getObjCObjectType(type, {}, protocols, false);
5854 }
5855
5856 // id<protocol-list>
5857 if (type->isObjCIdType()) {
5858 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
5859 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
5860 objPtr->isKindOfType());
5862 }
5863
5864 // Class<protocol-list>
5865 if (type->isObjCClassType()) {
5866 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
5867 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
5868 objPtr->isKindOfType());
5870 }
5871
5872 hasError = true;
5873 return type;
5874}
5875
5878 ArrayRef<ObjCProtocolDecl *> protocols) const {
5879 // Look in the folding set for an existing type.
5880 llvm::FoldingSetNodeID ID;
5881 ObjCTypeParamType::Profile(ID, Decl, Decl->getUnderlyingType(), protocols);
5882 void *InsertPos = nullptr;
5883 if (ObjCTypeParamType *TypeParam =
5884 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
5885 return QualType(TypeParam, 0);
5886
5887 // We canonicalize to the underlying type.
5888 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
5889 if (!protocols.empty()) {
5890 // Apply the protocol qualifers.
5891 bool hasError;
5893 Canonical, protocols, hasError, true /*allowOnPointerType*/));
5894 assert(!hasError && "Error when apply protocol qualifier to bound type");
5895 }
5896
5897 unsigned size = sizeof(ObjCTypeParamType);
5898 size += protocols.size() * sizeof(ObjCProtocolDecl *);
5899 void *mem = Allocate(size, alignof(ObjCTypeParamType));
5900 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
5901
5902 Types.push_back(newType);
5903 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
5904 return QualType(newType, 0);
5905}
5906
5908 ObjCTypeParamDecl *New) const {
5910 // Update TypeForDecl after updating TypeSourceInfo.
5911 auto NewTypeParamTy = cast<ObjCTypeParamType>(New->getTypeForDecl());
5913 protocols.append(NewTypeParamTy->qual_begin(), NewTypeParamTy->qual_end());
5914 QualType UpdatedTy = getObjCTypeParamType(New, protocols);
5915 New->setTypeForDecl(UpdatedTy.getTypePtr());
5916}
5917
5918/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
5919/// protocol list adopt all protocols in QT's qualified-id protocol
5920/// list.
5922 ObjCInterfaceDecl *IC) {
5923 if (!QT->isObjCQualifiedIdType())
5924 return false;
5925
5926 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
5927 // If both the right and left sides have qualifiers.
5928 for (auto *Proto : OPT->quals()) {
5929 if (!IC->ClassImplementsProtocol(Proto, false))
5930 return false;
5931 }
5932 return true;
5933 }
5934 return false;
5935}
5936
5937/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
5938/// QT's qualified-id protocol list adopt all protocols in IDecl's list
5939/// of protocols.
5941 ObjCInterfaceDecl *IDecl) {
5942 if (!QT->isObjCQualifiedIdType())
5943 return false;
5944 const auto *OPT = QT->getAs<ObjCObjectPointerType>();
5945 if (!OPT)
5946 return false;
5947 if (!IDecl->hasDefinition())
5948 return false;
5950 CollectInheritedProtocols(IDecl, InheritedProtocols);
5951 if (InheritedProtocols.empty())
5952 return false;
5953 // Check that if every protocol in list of id<plist> conforms to a protocol
5954 // of IDecl's, then bridge casting is ok.
5955 bool Conforms = false;
5956 for (auto *Proto : OPT->quals()) {
5957 Conforms = false;
5958 for (auto *PI : InheritedProtocols) {
5959 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
5960 Conforms = true;
5961 break;
5962 }
5963 }
5964 if (!Conforms)
5965 break;
5966 }
5967 if (Conforms)
5968 return true;
5969
5970 for (auto *PI : InheritedProtocols) {
5971 // If both the right and left sides have qualifiers.
5972 bool Adopts = false;
5973 for (auto *Proto : OPT->quals()) {
5974 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
5975 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
5976 break;
5977 }
5978 if (!Adopts)
5979 return false;
5980 }
5981 return true;
5982}
5983
5984/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
5985/// the given object type.
5987 llvm::FoldingSetNodeID ID;
5988 ObjCObjectPointerType::Profile(ID, ObjectT);
5989
5990 void *InsertPos = nullptr;
5991 if (ObjCObjectPointerType *QT =
5992 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
5993 return QualType(QT, 0);
5994
5995 // Find the canonical object type.
5996 QualType Canonical;
5997 if (!ObjectT.isCanonical()) {
5998 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
5999
6000 // Regenerate InsertPos.
6001 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
6002 }
6003
6004 // No match.
6005 void *Mem =
6007 auto *QType =
6008 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
6009
6010 Types.push_back(QType);
6011 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
6012 return QualType(QType, 0);
6013}
6014
6015/// getObjCInterfaceType - Return the unique reference to the type for the
6016/// specified ObjC interface decl. The list of protocols is optional.
6018 ObjCInterfaceDecl *PrevDecl) const {
6019 if (Decl->TypeForDecl)
6020 return QualType(Decl->TypeForDecl, 0);
6021
6022 if (PrevDecl) {
6023 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
6024 Decl->TypeForDecl = PrevDecl->TypeForDecl;
6025 return QualType(PrevDecl->TypeForDecl, 0);
6026 }
6027
6028 // Prefer the definition, if there is one.
6029 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
6030 Decl = Def;
6031
6032 void *Mem = Allocate(sizeof(ObjCInterfaceType), alignof(ObjCInterfaceType));
6033 auto *T = new (Mem) ObjCInterfaceType(Decl);
6034 Decl->TypeForDecl = T;
6035 Types.push_back(T);
6036 return QualType(T, 0);
6037}
6038
6039/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
6040/// TypeOfExprType AST's (since expression's are never shared). For example,
6041/// multiple declarations that refer to "typeof(x)" all contain different
6042/// DeclRefExpr's. This doesn't effect the type checker, since it operates
6043/// on canonical type's (which are always unique).
6045 TypeOfExprType *toe;
6046 if (tofExpr->isTypeDependent()) {
6047 llvm::FoldingSetNodeID ID;
6048 DependentTypeOfExprType::Profile(ID, *this, tofExpr,
6049 Kind == TypeOfKind::Unqualified);
6050
6051 void *InsertPos = nullptr;
6053 DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
6054 if (Canon) {
6055 // We already have a "canonical" version of an identical, dependent
6056 // typeof(expr) type. Use that as our canonical type.
6057 toe = new (*this, alignof(TypeOfExprType)) TypeOfExprType(
6058 *this, tofExpr, Kind, QualType((TypeOfExprType *)Canon, 0));
6059 } else {
6060 // Build a new, canonical typeof(expr) type.
6061 Canon = new (*this, alignof(DependentTypeOfExprType))
6062 DependentTypeOfExprType(*this, tofExpr, Kind);
6063 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
6064 toe = Canon;
6065 }
6066 } else {
6067 QualType Canonical = getCanonicalType(tofExpr->getType());
6068 toe = new (*this, alignof(TypeOfExprType))
6069 TypeOfExprType(*this, tofExpr, Kind, Canonical);
6070 }
6071 Types.push_back(toe);
6072 return QualType(toe, 0);
6073}
6074
6075/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
6076/// TypeOfType nodes. The only motivation to unique these nodes would be
6077/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
6078/// an issue. This doesn't affect the type checker, since it operates
6079/// on canonical types (which are always unique).
6081 QualType Canonical = getCanonicalType(tofType);
6082 auto *tot = new (*this, alignof(TypeOfType))
6083 TypeOfType(*this, tofType, Canonical, Kind);
6084 Types.push_back(tot);
6085 return QualType(tot, 0);
6086}
6087
6088/// getReferenceQualifiedType - Given an expr, will return the type for
6089/// that expression, as in [dcl.type.simple]p4 but without taking id-expressions
6090/// and class member access into account.
6092 // C++11 [dcl.type.simple]p4:
6093 // [...]
6094 QualType T = E->getType();
6095 switch (E->getValueKind()) {
6096 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
6097 // type of e;
6098 case VK_XValue:
6099 return getRValueReferenceType(T);
6100 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
6101 // type of e;
6102 case VK_LValue:
6103 return getLValueReferenceType(T);
6104 // - otherwise, decltype(e) is the type of e.
6105 case VK_PRValue:
6106 return T;
6107 }
6108 llvm_unreachable("Unknown value kind");
6109}
6110
6111/// Unlike many "get<Type>" functions, we don't unique DecltypeType
6112/// nodes. This would never be helpful, since each such type has its own
6113/// expression, and would not give a significant memory saving, since there
6114/// is an Expr tree under each such type.
6116 DecltypeType *dt;
6117
6118 // C++11 [temp.type]p2:
6119 // If an expression e involves a template parameter, decltype(e) denotes a
6120 // unique dependent type. Two such decltype-specifiers refer to the same
6121 // type only if their expressions are equivalent (14.5.6.1).
6122 if (e->isInstantiationDependent()) {
6123 llvm::FoldingSetNodeID ID;
6124 DependentDecltypeType::Profile(ID, *this, e);
6125
6126 void *InsertPos = nullptr;
6128 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
6129 if (!Canon) {
6130 // Build a new, canonical decltype(expr) type.
6131 Canon = new (*this, alignof(DependentDecltypeType))
6133 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
6134 }
6135 dt = new (*this, alignof(DecltypeType))
6136 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
6137 } else {
6138 dt = new (*this, alignof(DecltypeType))
6139 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
6140 }
6141 Types.push_back(dt);
6142 return QualType(dt, 0);
6143}
6144
6146 bool FullySubstituted,
6147 ArrayRef<QualType> Expansions,
6148 int Index) const {
6149 QualType Canonical;
6150 if (FullySubstituted && Index != -1) {
6151 Canonical = getCanonicalType(Expansions[Index]);
6152 } else {
6153 llvm::FoldingSetNodeID ID;
6154 PackIndexingType::Profile(ID, *this, Pattern, IndexExpr);
6155 void *InsertPos = nullptr;
6156 PackIndexingType *Canon =
6157 DependentPackIndexingTypes.FindNodeOrInsertPos(ID, InsertPos);
6158 if (!Canon) {
6159 void *Mem = Allocate(
6160 PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
6162 Canon = new (Mem)
6163 PackIndexingType(*this, QualType(), Pattern, IndexExpr, Expansions);
6164 DependentPackIndexingTypes.InsertNode(Canon, InsertPos);
6165 }
6166 Canonical = QualType(Canon, 0);
6167 }
6168
6169 void *Mem =
6170 Allocate(PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
6172 auto *T = new (Mem)
6173 PackIndexingType(*this, Canonical, Pattern, IndexExpr, Expansions);
6174 Types.push_back(T);
6175 return QualType(T, 0);
6176}
6177
6178/// getUnaryTransformationType - We don't unique these, since the memory
6179/// savings are minimal and these are rare.
6181 QualType UnderlyingType,
6183 const {
6184 UnaryTransformType *ut = nullptr;
6185
6186 if (BaseType->isDependentType()) {
6187 // Look in the folding set for an existing type.
6188 llvm::FoldingSetNodeID ID;
6190
6191 void *InsertPos = nullptr;
6193 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
6194
6195 if (!Canon) {
6196 // Build a new, canonical __underlying_type(type) type.
6197 Canon = new (*this, alignof(DependentUnaryTransformType))
6198 DependentUnaryTransformType(*this, getCanonicalType(BaseType), Kind);
6199 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
6200 }
6201 ut = new (*this, alignof(UnaryTransformType))
6202 UnaryTransformType(BaseType, QualType(), Kind, QualType(Canon, 0));
6203 } else {
6204 QualType CanonType = getCanonicalType(UnderlyingType);
6205 ut = new (*this, alignof(UnaryTransformType))
6206 UnaryTransformType(BaseType, UnderlyingType, Kind, CanonType);
6207 }
6208 Types.push_back(ut);
6209 return QualType(ut, 0);
6210}
6211
6212QualType ASTContext::getAutoTypeInternal(
6213 QualType DeducedType, AutoTypeKeyword Keyword, bool IsDependent,
6214 bool IsPack, ConceptDecl *TypeConstraintConcept,
6215 ArrayRef<TemplateArgument> TypeConstraintArgs, bool IsCanon) const {
6216 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto &&
6217 !TypeConstraintConcept && !IsDependent)
6218 return getAutoDeductType();
6219
6220 // Look in the folding set for an existing type.
6221 void *InsertPos = nullptr;
6222 llvm::FoldingSetNodeID ID;
6223 AutoType::Profile(ID, *this, DeducedType, Keyword, IsDependent,
6224 TypeConstraintConcept, TypeConstraintArgs);
6225 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
6226 return QualType(AT, 0);
6227
6228 QualType Canon;
6229 if (!IsCanon) {
6230 if (!DeducedType.isNull()) {
6231 Canon = DeducedType.getCanonicalType();
6232 } else if (TypeConstraintConcept) {
6233 bool AnyNonCanonArgs = false;
6234 ConceptDecl *CanonicalConcept = TypeConstraintConcept->getCanonicalDecl();
6235 auto CanonicalConceptArgs = ::getCanonicalTemplateArguments(
6236 *this, TypeConstraintArgs, AnyNonCanonArgs);
6237 if (CanonicalConcept != TypeConstraintConcept || AnyNonCanonArgs) {
6238 Canon =
6239 getAutoTypeInternal(QualType(), Keyword, IsDependent, IsPack,
6240 CanonicalConcept, CanonicalConceptArgs, true);
6241 // Find the insert position again.
6242 [[maybe_unused]] auto *Nothing =
6243 AutoTypes.FindNodeOrInsertPos(ID, InsertPos);
6244 assert(!Nothing && "canonical type broken");
6245 }
6246 }
6247 }
6248
6249 void *Mem = Allocate(sizeof(AutoType) +
6250 sizeof(TemplateArgument) * TypeConstraintArgs.size(),
6251 alignof(AutoType));
6252 auto *AT = new (Mem) AutoType(
6253 DeducedType, Keyword,
6254 (IsDependent ? TypeDependence::DependentInstantiation
6255 : TypeDependence::None) |
6256 (IsPack ? TypeDependence::UnexpandedPack : TypeDependence::None),
6257 Canon, TypeConstraintConcept, TypeConstraintArgs);
6258 Types.push_back(AT);
6259 AutoTypes.InsertNode(AT, InsertPos);
6260 return QualType(AT, 0);
6261}
6262
6263/// getAutoType - Return the uniqued reference to the 'auto' type which has been
6264/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
6265/// canonical deduced-but-dependent 'auto' type.
6268 bool IsDependent, bool IsPack,
6269 ConceptDecl *TypeConstraintConcept,
6270 ArrayRef<TemplateArgument> TypeConstraintArgs) const {
6271 assert((!IsPack || IsDependent) && "only use IsPack for a dependent pack");
6272 assert((!IsDependent || DeducedType.isNull()) &&
6273 "A dependent auto should be undeduced");
6274 return getAutoTypeInternal(DeducedType, Keyword, IsDependent, IsPack,
6275 TypeConstraintConcept, TypeConstraintArgs);
6276}
6277
6279 QualType CanonT = T.getCanonicalType();
6280
6281 // Remove a type-constraint from a top-level auto or decltype(auto).
6282 if (auto *AT = CanonT->getAs<AutoType>()) {
6283 if (!AT->isConstrained())
6284 return T;
6285 return getQualifiedType(getAutoType(QualType(), AT->getKeyword(),
6286 AT->isDependentType(),
6287 AT->containsUnexpandedParameterPack()),
6288 T.getQualifiers());
6289 }
6290
6291 // FIXME: We only support constrained auto at the top level in the type of a
6292 // non-type template parameter at the moment. Once we lift that restriction,
6293 // we'll need to recursively build types containing auto here.
6294 assert(!CanonT->getContainedAutoType() ||
6295 !CanonT->getContainedAutoType()->isConstrained());
6296 return T;
6297}
6298
6299QualType ASTContext::getDeducedTemplateSpecializationTypeInternal(
6300 TemplateName Template, QualType DeducedType, bool IsDependent,
6301 QualType Canon) const {
6302 // Look in the folding set for an existing type.
6303 void *InsertPos = nullptr;
6304 llvm::FoldingSetNodeID ID;
6306 IsDependent);
6308 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
6309 return QualType(DTST, 0);
6310
6311 auto *DTST = new (*this, alignof(DeducedTemplateSpecializationType))
6312 DeducedTemplateSpecializationType(Template, DeducedType, IsDependent,
6313 Canon);
6314 llvm::FoldingSetNodeID TempID;
6315 DTST->Profile(TempID);
6316 assert(ID == TempID && "ID does not match");
6317 Types.push_back(DTST);
6318 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
6319 return QualType(DTST, 0);
6320}
6321
6322/// Return the uniqued reference to the deduced template specialization type
6323/// which has been deduced to the given type, or to the canonical undeduced
6324/// such type, or the canonical deduced-but-dependent such type.
6326 TemplateName Template, QualType DeducedType, bool IsDependent) const {
6327 QualType Canon = DeducedType.isNull()
6328 ? getDeducedTemplateSpecializationTypeInternal(
6330 IsDependent, QualType())
6331 : DeducedType.getCanonicalType();
6332 return getDeducedTemplateSpecializationTypeInternal(Template, DeducedType,
6333 IsDependent, Canon);
6334}
6335
6336/// getAtomicType - Return the uniqued reference to the atomic type for
6337/// the given value type.
6339 // Unique pointers, to guarantee there is only one pointer of a particular
6340 // structure.
6341 llvm::FoldingSetNodeID ID;
6343
6344 void *InsertPos = nullptr;
6345 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
6346 return QualType(AT, 0);
6347
6348 // If the atomic value type isn't canonical, this won't be a canonical type
6349 // either, so fill in the canonical type field.
6350 QualType Canonical;
6351 if (!T.isCanonical()) {
6352 Canonical = getAtomicType(getCanonicalType(T));
6353
6354 // Get the new insert position for the node we care about.
6355 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
6356 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
6357 }
6358 auto *New = new (*this, alignof(AtomicType)) AtomicType(T, Canonical);
6359 Types.push_back(New);
6360 AtomicTypes.InsertNode(New, InsertPos);
6361 return QualType(New, 0);
6362}
6363
6364/// getAutoDeductType - Get type pattern for deducing against 'auto'.
6366 if (AutoDeductTy.isNull())
6367 AutoDeductTy = QualType(new (*this, alignof(AutoType))
6369 TypeDependence::None, QualType(),
6370 /*concept*/ nullptr, /*args*/ {}),
6371 0);
6372 return AutoDeductTy;
6373}
6374
6375/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
6379 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
6380 return AutoRRefDeductTy;
6381}
6382
6383/// getTagDeclType - Return the unique reference to the type for the
6384/// specified TagDecl (struct/union/class/enum) decl.
6386 assert(Decl);
6387 // FIXME: What is the design on getTagDeclType when it requires casting
6388 // away const? mutable?
6389 return getTypeDeclType(const_cast<TagDecl*>(Decl));
6390}
6391
6392/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
6393/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
6394/// needs to agree with the definition in <stddef.h>.
6396 return getFromTargetType(Target->getSizeType());
6397}
6398
6399/// Return the unique signed counterpart of the integer type
6400/// corresponding to size_t.
6402 return getFromTargetType(Target->getSignedSizeType());
6403}
6404
6405/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
6407 return getFromTargetType(Target->getIntMaxType());
6408}
6409
6410/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
6412 return getFromTargetType(Target->getUIntMaxType());
6413}
6414
6415/// getSignedWCharType - Return the type of "signed wchar_t".
6416/// Used when in C++, as a GCC extension.
6418 // FIXME: derive from "Target" ?
6419 return WCharTy;
6420}
6421
6422/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
6423/// Used when in C++, as a GCC extension.
6425 // FIXME: derive from "Target" ?
6426 return UnsignedIntTy;
6427}
6428
6430 return getFromTargetType(Target->getIntPtrType());
6431}
6432
6435}
6436
6437/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
6438/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
6440 return getFromTargetType(Target->getPtrDiffType(LangAS::Default));
6441}
6442
6443/// Return the unique unsigned counterpart of "ptrdiff_t"
6444/// integer type. The standard (C11 7.21.6.1p7) refers to this type
6445/// in the definition of %tu format specifier.
6447 return getFromTargetType(Target->getUnsignedPtrDiffType(LangAS::Default));
6448}
6449
6450/// Return the unique type for "pid_t" defined in
6451/// <sys/types.h>. We need this to compute the correct type for vfork().
6453 return getFromTargetType(Target->getProcessIDType());
6454}
6455
6456//===----------------------------------------------------------------------===//
6457// Type Operators
6458//===----------------------------------------------------------------------===//
6459
6461 // Push qualifiers into arrays, and then discard any remaining
6462 // qualifiers.
6463 T = getCanonicalType(T);
6465 const Type *Ty = T.getTypePtr();
6467 if (getLangOpts().HLSL && isa<ConstantArrayType>(Ty)) {
6469 } else if (isa<ArrayType>(Ty)) {
6471 } else if (isa<FunctionType>(Ty)) {
6472 Result = getPointerType(QualType(Ty, 0));
6473 } else {
6474 Result = QualType(Ty, 0);
6475 }
6476
6478}
6479
6481 Qualifiers &quals) const {
6482 SplitQualType splitType = type.getSplitUnqualifiedType();
6483
6484 // FIXME: getSplitUnqualifiedType() actually walks all the way to
6485 // the unqualified desugared type and then drops it on the floor.
6486 // We then have to strip that sugar back off with
6487 // getUnqualifiedDesugaredType(), which is silly.
6488 const auto *AT =
6489 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
6490
6491 // If we don't have an array, just use the results in splitType.
6492 if (!AT) {
6493 quals = splitType.Quals;
6494 return QualType(splitType.Ty, 0);
6495 }
6496
6497 // Otherwise, recurse on the array's element type.
6498 QualType elementType = AT->getElementType();
6499 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
6500
6501 // If that didn't change the element type, AT has no qualifiers, so we
6502 // can just use the results in splitType.
6503 if (elementType == unqualElementType) {
6504 assert(quals.empty()); // from the recursive call
6505 quals = splitType.Quals;
6506 return QualType(splitType.Ty, 0);
6507 }
6508
6509 // Otherwise, add in the qualifiers from the outermost type, then
6510 // build the type back up.
6511 quals.addConsistentQualifiers(splitType.Quals);
6512
6513 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
6514 return getConstantArrayType(unqualElementType, CAT->getSize(),
6515 CAT->getSizeExpr(), CAT->getSizeModifier(), 0);
6516 }
6517
6518 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
6519 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
6520 }
6521
6522 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
6523 return getVariableArrayType(unqualElementType,
6524 VAT->getSizeExpr(),
6525 VAT->getSizeModifier(),
6526 VAT->getIndexTypeCVRQualifiers(),
6527 VAT->getBracketsRange());
6528 }
6529
6530 const auto *DSAT = cast<DependentSizedArrayType>(AT);
6531 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
6532 DSAT->getSizeModifier(), 0,
6533 SourceRange());
6534}
6535
6536/// Attempt to unwrap two types that may both be array types with the same bound
6537/// (or both be array types of unknown bound) for the purpose of comparing the
6538/// cv-decomposition of two types per C++ [conv.qual].
6539///
6540/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
6541/// C++20 [conv.qual], if permitted by the current language mode.
6543 bool AllowPiMismatch) {
6544 while (true) {
6545 auto *AT1 = getAsArrayType(T1);
6546 if (!AT1)
6547 return;
6548
6549 auto *AT2 = getAsArrayType(T2);
6550 if (!AT2)
6551 return;
6552
6553 // If we don't have two array types with the same constant bound nor two
6554 // incomplete array types, we've unwrapped everything we can.
6555 // C++20 also permits one type to be a constant array type and the other
6556 // to be an incomplete array type.
6557 // FIXME: Consider also unwrapping array of unknown bound and VLA.
6558 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
6559 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
6560 if (!((CAT2 && CAT1->getSize() == CAT2->getSize()) ||
6561 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
6562 isa<IncompleteArrayType>(AT2))))
6563 return;
6564 } else if (isa<IncompleteArrayType>(AT1)) {
6565 if (!(isa<IncompleteArrayType>(AT2) ||
6566 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
6567 isa<ConstantArrayType>(AT2))))
6568 return;
6569 } else {
6570 return;
6571 }
6572
6573 T1 = AT1->getElementType();
6574 T2 = AT2->getElementType();
6575 }
6576}
6577
6578/// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
6579///
6580/// If T1 and T2 are both pointer types of the same kind, or both array types
6581/// with the same bound, unwraps layers from T1 and T2 until a pointer type is
6582/// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
6583///
6584/// This function will typically be called in a loop that successively
6585/// "unwraps" pointer and pointer-to-member types to compare them at each
6586/// level.
6587///
6588/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
6589/// C++20 [conv.qual], if permitted by the current language mode.
6590///
6591/// \return \c true if a pointer type was unwrapped, \c false if we reached a
6592/// pair of types that can't be unwrapped further.
6594 bool AllowPiMismatch) {
6595 UnwrapSimilarArrayTypes(T1, T2, AllowPiMismatch);
6596
6597 const auto *T1PtrType = T1->getAs<PointerType>();
6598 const auto *T2PtrType = T2->getAs<PointerType>();
6599 if (T1PtrType && T2PtrType) {
6600 T1 = T1PtrType->getPointeeType();
6601 T2 = T2PtrType->getPointeeType();
6602 return true;
6603 }
6604
6605 const auto *T1MPType = T1->getAs<MemberPointerType>();
6606 const auto *T2MPType = T2->getAs<MemberPointerType>();
6607 if (T1MPType && T2MPType &&
6608 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
6609 QualType(T2MPType->getClass(), 0))) {
6610 T1 = T1MPType->getPointeeType();
6611 T2 = T2MPType->getPointeeType();
6612 return true;
6613 }
6614
6615 if (getLangOpts().ObjC) {
6616 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
6617 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
6618 if (T1OPType && T2OPType) {
6619 T1 = T1OPType->getPointeeType();
6620 T2 = T2OPType->getPointeeType();
6621 return true;
6622 }
6623 }
6624
6625 // FIXME: Block pointers, too?
6626
6627 return false;
6628}
6629
6631 while (true) {
6632 Qualifiers Quals;
6633 T1 = getUnqualifiedArrayType(T1, Quals);
6634 T2 = getUnqualifiedArrayType(T2, Quals);
6635 if (hasSameType(T1, T2))
6636 return true;
6637 if (!UnwrapSimilarTypes(T1, T2))
6638 return false;
6639 }
6640}
6641
6643 while (true) {
6644 Qualifiers Quals1, Quals2;
6645 T1 = getUnqualifiedArrayType(T1, Quals1);
6646 T2 = getUnqualifiedArrayType(T2, Quals2);
6647
6648 Quals1.removeCVRQualifiers();
6649 Quals2.removeCVRQualifiers();
6650 if (Quals1 != Quals2)
6651 return false;
6652
6653 if (hasSameType(T1, T2))
6654 return true;
6655
6656 if (!UnwrapSimilarTypes(T1, T2, /*AllowPiMismatch*/ false))
6657 return false;
6658 }
6659}
6660
6663 SourceLocation NameLoc) const {
6664 switch (Name.getKind()) {
6667 // DNInfo work in progress: CHECKME: what about DNLoc?
6668 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
6669 NameLoc);
6670
6672 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
6673 // DNInfo work in progress: CHECKME: what about DNLoc?
6674 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
6675 }
6676
6678 AssumedTemplateStorage *Storage = Name.getAsAssumedTemplateName();
6679 return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
6680 }
6681
6683 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
6684 DeclarationName DName;
6685 if (DTN->isIdentifier()) {
6687 return DeclarationNameInfo(DName, NameLoc);
6688 } else {
6690 // DNInfo work in progress: FIXME: source locations?
6691 DeclarationNameLoc DNLoc =
6693 return DeclarationNameInfo(DName, NameLoc, DNLoc);
6694 }
6695 }
6696
6699 = Name.getAsSubstTemplateTemplateParm();
6700 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
6701 NameLoc);
6702 }
6703
6706 = Name.getAsSubstTemplateTemplateParmPack();
6708 NameLoc);
6709 }
6711 return DeclarationNameInfo(Name.getAsUsingShadowDecl()->getDeclName(),
6712 NameLoc);
6713 }
6714
6715 llvm_unreachable("bad template name kind!");
6716}
6717
6720 switch (Name.getKind()) {
6724 TemplateDecl *Template = Name.getAsTemplateDecl();
6725 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template))
6726 Template = getCanonicalTemplateTemplateParmDecl(TTP);
6727
6728 // The canonical template name is the canonical template declaration.
6729 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
6730 }
6731
6734 llvm_unreachable("cannot canonicalize unresolved template");
6735
6737 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
6738 assert(DTN && "Non-dependent template names must refer to template decls.");
6739 return DTN->CanonicalTemplateName;
6740 }
6741
6744 = Name.getAsSubstTemplateTemplateParm();
6746 }
6747
6750 Name.getAsSubstTemplateTemplateParmPack();
6751 TemplateArgument canonArgPack =
6754 canonArgPack, subst->getAssociatedDecl()->getCanonicalDecl(),
6755 subst->getFinal(), subst->getIndex());
6756 }
6757 }
6758
6759 llvm_unreachable("bad template name!");
6760}
6761
6763 const TemplateName &Y) const {
6766}
6767
6768bool ASTContext::isSameConstraintExpr(const Expr *XCE, const Expr *YCE) const {
6769 if (!XCE != !YCE)
6770 return false;
6771
6772 if (!XCE)
6773 return true;
6774
6775 llvm::FoldingSetNodeID XCEID, YCEID;
6776 XCE->Profile(XCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
6777 YCE->Profile(YCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
6778 return XCEID == YCEID;
6779}
6780
6782 const TypeConstraint *YTC) const {
6783 if (!XTC != !YTC)
6784 return false;
6785
6786 if (!XTC)
6787 return true;
6788
6789 auto *NCX = XTC->getNamedConcept();
6790 auto *NCY = YTC->getNamedConcept();
6791 if (!NCX || !NCY || !isSameEntity(NCX, NCY))
6792 return false;
6795 return false;
6797 if (XTC->getConceptReference()
6799 ->NumTemplateArgs !=
6801 return false;
6802
6803 // Compare slowly by profiling.
6804 //
6805 // We couldn't compare the profiling result for the template
6806 // args here. Consider the following example in different modules:
6807 //
6808 // template <__integer_like _Tp, C<_Tp> Sentinel>
6809 // constexpr _Tp operator()(_Tp &&__t, Sentinel &&last) const {
6810 // return __t;
6811 // }
6812 //
6813 // When we compare the profiling result for `C<_Tp>` in different
6814 // modules, it will compare the type of `_Tp` in different modules.
6815 // However, the type of `_Tp` in different modules refer to different
6816 // types here naturally. So we couldn't compare the profiling result
6817 // for the template args directly.
6820}
6821
6823 const NamedDecl *Y) const {
6824 if (X->getKind() != Y->getKind())
6825 return false;
6826
6827 if (auto *TX = dyn_cast<TemplateTypeParmDecl>(X)) {
6828 auto *TY = cast<TemplateTypeParmDecl>(Y);
6829 if (TX->isParameterPack() != TY->isParameterPack())
6830 return false;
6831 if (TX->hasTypeConstraint() != TY->hasTypeConstraint())
6832 return false;
6833 return isSameTypeConstraint(TX->getTypeConstraint(),
6834 TY->getTypeConstraint());
6835 }
6836
6837 if (auto *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
6838 auto *TY = cast<NonTypeTemplateParmDecl>(Y);
6839 return TX->isParameterPack() == TY->isParameterPack() &&
6840 TX->getASTContext().hasSameType(TX->getType(), TY->getType()) &&
6841 isSameConstraintExpr(TX->getPlaceholderTypeConstraint(),
6842 TY->getPlaceholderTypeConstraint());
6843 }
6844
6845 auto *TX = cast<TemplateTemplateParmDecl>(X);
6846 auto *TY = cast<TemplateTemplateParmDecl>(Y);
6847 return TX->isParameterPack() == TY->isParameterPack() &&
6848 isSameTemplateParameterList(TX->getTemplateParameters(),
6849 TY->getTemplateParameters());
6850}
6851
6853 const TemplateParameterList *X, const TemplateParameterList *Y) const {
6854 if (X->size() != Y->size())
6855 return false;
6856
6857 for (unsigned I = 0, N = X->size(); I != N; ++I)
6858 if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I)))
6859 return false;
6860
6861 return isSameConstraintExpr(X->getRequiresClause(), Y->getRequiresClause());
6862}
6863
6865 const NamedDecl *Y) const {
6866 // If the type parameter isn't the same already, we don't need to check the
6867 // default argument further.
6868 if (!isSameTemplateParameter(X, Y))
6869 return false;
6870
6871 if (auto *TTPX = dyn_cast<TemplateTypeParmDecl>(X)) {
6872 auto *TTPY = cast<TemplateTypeParmDecl>(Y);
6873 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
6874 return false;
6875
6876 return hasSameType(TTPX->getDefaultArgument().getArgument().getAsType(),
6877 TTPY->getDefaultArgument().getArgument().getAsType());
6878 }
6879
6880 if (auto *NTTPX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
6881 auto *NTTPY = cast<NonTypeTemplateParmDecl>(Y);
6882 if (!NTTPX->hasDefaultArgument() || !NTTPY->hasDefaultArgument())
6883 return false;
6884
6885 Expr *DefaultArgumentX =
6886 NTTPX->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
6887 Expr *DefaultArgumentY =
6888 NTTPY->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
6889 llvm::FoldingSetNodeID XID, YID;
6890 DefaultArgumentX->Profile(XID, *this, /*Canonical=*/true);
6891 DefaultArgumentY->Profile(YID, *this, /*Canonical=*/true);
6892 return XID == YID;
6893 }
6894
6895 auto *TTPX = cast<TemplateTemplateParmDecl>(X);
6896 auto *TTPY = cast<TemplateTemplateParmDecl>(Y);
6897
6898 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
6899 return false;
6900
6901 const TemplateArgument &TAX = TTPX->getDefaultArgument().getArgument();
6902 const TemplateArgument &TAY = TTPY->getDefaultArgument().getArgument();
6903 return hasSameTemplateName(TAX.getAsTemplate(), TAY.getAsTemplate());
6904}
6905
6907 if (auto *NS = X->getAsNamespace())
6908 return NS;
6909 if (auto *NAS = X->getAsNamespaceAlias())
6910 return NAS->getNamespace();
6911 return nullptr;
6912}
6913
6915 const NestedNameSpecifier *Y) {
6916 if (auto *NSX = getNamespace(X)) {
6917 auto *NSY = getNamespace(Y);
6918 if (!NSY || NSX->getCanonicalDecl() != NSY->getCanonicalDecl())
6919 return false;
6920 } else if (X->getKind() != Y->getKind())
6921 return false;
6922
6923 // FIXME: For namespaces and types, we're permitted to check that the entity
6924 // is named via the same tokens. We should probably do so.
6925 switch (X->getKind()) {
6927 if (X->getAsIdentifier() != Y->getAsIdentifier())
6928 return false;
6929 break;
6932 // We've already checked that we named the same namespace.
6933 break;
6936 if (X->getAsType()->getCanonicalTypeInternal() !=
6938 return false;
6939 break;
6942 return true;
6943 }
6944
6945 // Recurse into earlier portion of NNS, if any.
6946 auto *PX = X->getPrefix();
6947 auto *PY = Y->getPrefix();
6948 if (PX && PY)
6949 return isSameQualifier(PX, PY);
6950 return !PX && !PY;
6951}
6952
6953/// Determine whether the attributes we can overload on are identical for A and
6954/// B. Will ignore any overloadable attrs represented in the type of A and B.
6956 const FunctionDecl *B) {
6957 // Note that pass_object_size attributes are represented in the function's
6958 // ExtParameterInfo, so we don't need to check them here.
6959
6960 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
6961 auto AEnableIfAttrs = A->specific_attrs<EnableIfAttr>();
6962 auto BEnableIfAttrs = B->specific_attrs<EnableIfAttr>();
6963
6964 for (auto Pair : zip_longest(AEnableIfAttrs, BEnableIfAttrs)) {
6965 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
6966 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
6967
6968 // Return false if the number of enable_if attributes is different.
6969 if (!Cand1A || !Cand2A)
6970 return false;
6971
6972 Cand1ID.clear();
6973 Cand2ID.clear();
6974
6975 (*Cand1A)->getCond()->Profile(Cand1ID, A->getASTContext(), true);
6976 (*Cand2A)->getCond()->Profile(Cand2ID, B->getASTContext(), true);
6977
6978 // Return false if any of the enable_if expressions of A and B are
6979 // different.
6980 if (Cand1ID != Cand2ID)
6981 return false;
6982 }
6983 return true;
6984}
6985
6986bool ASTContext::isSameEntity(const NamedDecl *X, const NamedDecl *Y) const {
6987 // Caution: this function is called by the AST reader during deserialization,
6988 // so it cannot rely on AST invariants being met. Non-trivial accessors
6989 // should be avoided, along with any traversal of redeclaration chains.
6990
6991 if (X == Y)
6992 return true;
6993
6994 if (X->getDeclName() != Y->getDeclName())
6995 return false;
6996
6997 // Must be in the same context.
6998 //
6999 // Note that we can't use DeclContext::Equals here, because the DeclContexts
7000 // could be two different declarations of the same function. (We will fix the
7001 // semantic DC to refer to the primary definition after merging.)
7002 if (!declaresSameEntity(cast<Decl>(X->getDeclContext()->getRedeclContext()),
7003 cast<Decl>(Y->getDeclContext()->getRedeclContext())))
7004 return false;
7005
7006 // Two typedefs refer to the same entity if they have the same underlying
7007 // type.
7008 if (const auto *TypedefX = dyn_cast<TypedefNameDecl>(X))
7009 if (const auto *TypedefY = dyn_cast<TypedefNameDecl>(Y))
7010 return hasSameType(TypedefX->getUnderlyingType(),
7011 TypedefY->getUnderlyingType());
7012
7013 // Must have the same kind.
7014 if (X->getKind() != Y->getKind())
7015 return false;
7016
7017 // Objective-C classes and protocols with the same name always match.
7018 if (isa<ObjCInterfaceDecl>(X) || isa<ObjCProtocolDecl>(X))
7019 return true;
7020
7021 if (isa<ClassTemplateSpecializationDecl>(X)) {
7022 // No need to handle these here: we merge them when adding them to the
7023 // template.
7024 return false;
7025 }
7026
7027 // Compatible tags match.
7028 if (const auto *TagX = dyn_cast<TagDecl>(X)) {
7029 const auto *TagY = cast<TagDecl>(Y);
7030 return (TagX->getTagKind() == TagY->getTagKind()) ||
7031 ((TagX->getTagKind() == TagTypeKind::Struct ||
7032 TagX->getTagKind() == TagTypeKind::Class ||
7033 TagX->getTagKind() == TagTypeKind::Interface) &&
7034 (TagY->getTagKind() == TagTypeKind::Struct ||
7035 TagY->getTagKind() == TagTypeKind::Class ||
7036 TagY->getTagKind() == TagTypeKind::Interface));
7037 }
7038
7039 // Functions with the same type and linkage match.
7040 // FIXME: This needs to cope with merging of prototyped/non-prototyped
7041 // functions, etc.
7042 if (const auto *FuncX = dyn_cast<FunctionDecl>(X)) {
7043 const auto *FuncY = cast<FunctionDecl>(Y);
7044 if (const auto *CtorX = dyn_cast<CXXConstructorDecl>(X)) {
7045 const auto *CtorY = cast<CXXConstructorDecl>(Y);
7046 if (CtorX->getInheritedConstructor() &&
7047 !isSameEntity(CtorX->getInheritedConstructor().getConstructor(),
7048 CtorY->getInheritedConstructor().getConstructor()))
7049 return false;
7050 }
7051
7052 if (FuncX->isMultiVersion() != FuncY->isMultiVersion())
7053 return false;
7054
7055 // Multiversioned functions with different feature strings are represented
7056 // as separate declarations.
7057 if (FuncX->isMultiVersion()) {
7058 const auto *TAX = FuncX->getAttr<TargetAttr>();
7059 const auto *TAY = FuncY->getAttr<TargetAttr>();
7060 assert(TAX && TAY && "Multiversion Function without target attribute");
7061
7062 if (TAX->getFeaturesStr() != TAY->getFeaturesStr())
7063 return false;
7064 }
7065
7066 // Per C++20 [temp.over.link]/4, friends in different classes are sometimes
7067 // not the same entity if they are constrained.
7068 if ((FuncX->isMemberLikeConstrainedFriend() ||
7069 FuncY->isMemberLikeConstrainedFriend()) &&
7070 !FuncX->getLexicalDeclContext()->Equals(
7071 FuncY->getLexicalDeclContext())) {
7072 return false;
7073 }
7074
7075 if (!isSameConstraintExpr(FuncX->getTrailingRequiresClause(),
7076 FuncY->getTrailingRequiresClause()))
7077 return false;
7078
7079 auto GetTypeAsWritten = [](const FunctionDecl *FD) {
7080 // Map to the first declaration that we've already merged into this one.
7081 // The TSI of redeclarations might not match (due to calling conventions
7082 // being inherited onto the type but not the TSI), but the TSI type of
7083 // the first declaration of the function should match across modules.
7084 FD = FD->getCanonicalDecl();
7085 return FD->getTypeSourceInfo() ? FD->getTypeSourceInfo()->getType()
7086 : FD->getType();
7087 };
7088 QualType XT = GetTypeAsWritten(FuncX), YT = GetTypeAsWritten(FuncY);
7089 if (!hasSameType(XT, YT)) {
7090 // We can get functions with different types on the redecl chain in C++17
7091 // if they have differing exception specifications and at least one of
7092 // the excpetion specs is unresolved.
7093 auto *XFPT = XT->getAs<FunctionProtoType>();
7094 auto *YFPT = YT->getAs<FunctionProtoType>();
7095 if (getLangOpts().CPlusPlus17 && XFPT && YFPT &&
7096 (isUnresolvedExceptionSpec(XFPT->getExceptionSpecType()) ||
7099 return true;
7100 return false;
7101 }
7102
7103 return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() &&
7104 hasSameOverloadableAttrs(FuncX, FuncY);
7105 }
7106
7107 // Variables with the same type and linkage match.
7108 if (const auto *VarX = dyn_cast<VarDecl>(X)) {
7109 const auto *VarY = cast<VarDecl>(Y);
7110 if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) {
7111 // During deserialization, we might compare variables before we load
7112 // their types. Assume the types will end up being the same.
7113 if (VarX->getType().isNull() || VarY->getType().isNull())
7114 return true;
7115
7116 if (hasSameType(VarX->getType(), VarY->getType()))
7117 return true;
7118
7119 // We can get decls with different types on the redecl chain. Eg.
7120 // template <typename T> struct S { static T Var[]; }; // #1
7121 // template <typename T> T S<T>::Var[sizeof(T)]; // #2
7122 // Only? happens when completing an incomplete array type. In this case
7123 // when comparing #1 and #2 we should go through their element type.
7124 const ArrayType *VarXTy = getAsArrayType(VarX->getType());
7125 const ArrayType *VarYTy = getAsArrayType(VarY->getType());
7126 if (!VarXTy || !VarYTy)
7127 return false;
7128 if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType())
7129 return hasSameType(VarXTy->getElementType(), VarYTy->getElementType());
7130 }
7131 return false;
7132 }
7133
7134 // Namespaces with the same name and inlinedness match.
7135 if (const auto *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
7136 const auto *NamespaceY = cast<NamespaceDecl>(Y);
7137 return NamespaceX->isInline() == NamespaceY->isInline();
7138 }
7139
7140 // Identical template names and kinds match if their template parameter lists
7141 // and patterns match.
7142 if (const auto *TemplateX = dyn_cast<TemplateDecl>(X)) {
7143 const auto *TemplateY = cast<TemplateDecl>(Y);
7144
7145 // ConceptDecl wouldn't be the same if their constraint expression differs.
7146 if (const auto *ConceptX = dyn_cast<ConceptDecl>(X)) {
7147 const auto *ConceptY = cast<ConceptDecl>(Y);
7148 if (!isSameConstraintExpr(ConceptX->getConstraintExpr(),
7149 ConceptY->getConstraintExpr()))
7150 return false;
7151 }
7152
7153 return isSameEntity(TemplateX->getTemplatedDecl(),
7154 TemplateY->getTemplatedDecl()) &&
7155 isSameTemplateParameterList(TemplateX->getTemplateParameters(),
7156 TemplateY->getTemplateParameters());
7157 }
7158
7159 // Fields with the same name and the same type match.
7160 if (const auto *FDX = dyn_cast<FieldDecl>(X)) {
7161 const auto *FDY = cast<FieldDecl>(Y);
7162 // FIXME: Also check the bitwidth is odr-equivalent, if any.
7163 return hasSameType(FDX->getType(), FDY->getType());
7164 }
7165
7166 // Indirect fields with the same target field match.
7167 if (const auto *IFDX = dyn_cast<IndirectFieldDecl>(X)) {
7168 const auto *IFDY = cast<IndirectFieldDecl>(Y);
7169 return IFDX->getAnonField()->getCanonicalDecl() ==
7170 IFDY->getAnonField()->getCanonicalDecl();
7171 }
7172
7173 // Enumerators with the same name match.
7174 if (isa<EnumConstantDecl>(X))
7175 // FIXME: Also check the value is odr-equivalent.
7176 return true;
7177
7178 // Using shadow declarations with the same target match.
7179 if (const auto *USX = dyn_cast<UsingShadowDecl>(X)) {
7180 const auto *USY = cast<UsingShadowDecl>(Y);
7181 return declaresSameEntity(USX->getTargetDecl(), USY->getTargetDecl());
7182 }
7183
7184 // Using declarations with the same qualifier match. (We already know that
7185 // the name matches.)
7186 if (const auto *UX = dyn_cast<UsingDecl>(X)) {
7187 const auto *UY = cast<UsingDecl>(Y);
7188 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7189 UX->hasTypename() == UY->hasTypename() &&
7190 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7191 }
7192 if (const auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) {
7193 const auto *UY = cast<UnresolvedUsingValueDecl>(Y);
7194 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7195 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7196 }
7197 if (const auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X)) {
7198 return isSameQualifier(
7199 UX->getQualifier(),
7200 cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier());
7201 }
7202
7203 // Using-pack declarations are only created by instantiation, and match if
7204 // they're instantiated from matching UnresolvedUsing...Decls.
7205 if (const auto *UX = dyn_cast<UsingPackDecl>(X)) {
7206 return declaresSameEntity(
7207 UX->getInstantiatedFromUsingDecl(),
7208 cast<UsingPackDecl>(Y)->getInstantiatedFromUsingDecl());
7209 }
7210
7211 // Namespace alias definitions with the same target match.
7212 if (const auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) {
7213 const auto *NAY = cast<NamespaceAliasDecl>(Y);
7214 return NAX->getNamespace()->Equals(NAY->getNamespace());
7215 }
7216
7217 return false;
7218}
7219
7222 switch (Arg.getKind()) {
7224 return Arg;
7225
7227 return Arg;
7228
7230 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
7232 Arg.getIsDefaulted());
7233 }
7234
7237 /*isNullPtr*/ true, Arg.getIsDefaulted());
7238
7241 Arg.getIsDefaulted());
7242
7244 return TemplateArgument(
7247
7250
7252 return TemplateArgument(*this,
7254 Arg.getAsStructuralValue());
7255
7258 /*isNullPtr*/ false, Arg.getIsDefaulted());
7259
7261 bool AnyNonCanonArgs = false;
7262 auto CanonArgs = ::getCanonicalTemplateArguments(
7263 *this, Arg.pack_elements(), AnyNonCanonArgs);
7264 if (!AnyNonCanonArgs)
7265 return Arg;
7266 return TemplateArgument::CreatePackCopy(const_cast<ASTContext &>(*this),
7267 CanonArgs);
7268 }
7269 }
7270
7271 // Silence GCC warning
7272 llvm_unreachable("Unhandled template argument kind");
7273}
7274
7277 if (!NNS)
7278 return nullptr;
7279
7280 switch (NNS->getKind()) {
7282 // Canonicalize the prefix but keep the identifier the same.
7283 return NestedNameSpecifier::Create(*this,
7285 NNS->getAsIdentifier());
7286
7288 // A namespace is canonical; build a nested-name-specifier with
7289 // this namespace and no prefix.
7290 return NestedNameSpecifier::Create(*this, nullptr,
7291 NNS->getAsNamespace()->getFirstDecl());
7292
7294 // A namespace is canonical; build a nested-name-specifier with
7295 // this namespace and no prefix.
7297 *this, nullptr,
7299
7300 // The difference between TypeSpec and TypeSpecWithTemplate is that the
7301 // latter will have the 'template' keyword when printed.
7304 const Type *T = getCanonicalType(NNS->getAsType());
7305
7306 // If we have some kind of dependent-named type (e.g., "typename T::type"),
7307 // break it apart into its prefix and identifier, then reconsititute those
7308 // as the canonical nested-name-specifier. This is required to canonicalize
7309 // a dependent nested-name-specifier involving typedefs of dependent-name
7310 // types, e.g.,
7311 // typedef typename T::type T1;
7312 // typedef typename T1::type T2;
7313 if (const auto *DNT = T->getAs<DependentNameType>())
7314 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
7315 DNT->getIdentifier());
7316 if (const auto *DTST = T->getAs<DependentTemplateSpecializationType>())
7317 return NestedNameSpecifier::Create(*this, DTST->getQualifier(), true, T);
7318
7319 // TODO: Set 'Template' parameter to true for other template types.
7320 return NestedNameSpecifier::Create(*this, nullptr, false, T);
7321 }
7322
7325 // The global specifier and __super specifer are canonical and unique.
7326 return NNS;
7327 }
7328
7329 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
7330}
7331
7333 // Handle the non-qualified case efficiently.
7334 if (!T.hasLocalQualifiers()) {
7335 // Handle the common positive case fast.
7336 if (const auto *AT = dyn_cast<ArrayType>(T))
7337 return AT;
7338 }
7339
7340 // Handle the common negative case fast.
7341 if (!isa<ArrayType>(T.getCanonicalType()))
7342 return nullptr;
7343
7344 // Apply any qualifiers from the array type to the element type. This
7345 // implements C99 6.7.3p8: "If the specification of an array type includes
7346 // any type qualifiers, the element type is so qualified, not the array type."
7347
7348 // If we get here, we either have type qualifiers on the type, or we have
7349 // sugar such as a typedef in the way. If we have type qualifiers on the type
7350 // we must propagate them down into the element type.
7351
7352 SplitQualType split = T.getSplitDesugaredType();
7353 Qualifiers qs = split.Quals;
7354
7355 // If we have a simple case, just return now.
7356 const auto *ATy = dyn_cast<ArrayType>(split.Ty);
7357 if (!ATy || qs.empty())
7358 return ATy;
7359
7360 // Otherwise, we have an array and we have qualifiers on it. Push the
7361 // qualifiers into the array element type and return a new array type.
7362 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
7363
7364 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
7365 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
7366 CAT->getSizeExpr(),
7367 CAT->getSizeModifier(),
7368 CAT->getIndexTypeCVRQualifiers()));
7369 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
7370 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
7371 IAT->getSizeModifier(),
7372 IAT->getIndexTypeCVRQualifiers()));
7373
7374 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
7375 return cast<ArrayType>(
7377 DSAT->getSizeExpr(),
7378 DSAT->getSizeModifier(),
7379 DSAT->getIndexTypeCVRQualifiers(),
7380 DSAT->getBracketsRange()));
7381
7382 const auto *VAT = cast<VariableArrayType>(ATy);
7383 return cast<ArrayType>(getVariableArrayType(NewEltTy,
7384 VAT->getSizeExpr(),
7385 VAT->getSizeModifier(),
7386 VAT->getIndexTypeCVRQualifiers(),
7387 VAT->getBracketsRange()));
7388}
7389
7392 return getArrayParameterType(T);
7393 if (T->isArrayType() || T->isFunctionType())
7394 return getDecayedType(T);
7395 return T;
7396}
7397
7401 return T.getUnqualifiedType();
7402}
7403
7405 // C++ [except.throw]p3:
7406 // A throw-expression initializes a temporary object, called the exception
7407 // object, the type of which is determined by removing any top-level
7408 // cv-qualifiers from the static type of the operand of throw and adjusting
7409 // the type from "array of T" or "function returning T" to "pointer to T"
7410 // or "pointer to function returning T", [...]
7412 if (T->isArrayType() || T->isFunctionType())
7413 T = getDecayedType(T);
7414 return T.getUnqualifiedType();
7415}
7416
7417/// getArrayDecayedType - Return the properly qualified result of decaying the
7418/// specified array type to a pointer. This operation is non-trivial when
7419/// handling typedefs etc. The canonical type of "T" must be an array type,
7420/// this returns a pointer to a properly qualified element of the array.
7421///
7422/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
7424 // Get the element type with 'getAsArrayType' so that we don't lose any
7425 // typedefs in the element type of the array. This also handles propagation
7426 // of type qualifiers from the array type into the element type if present
7427 // (C99 6.7.3p8).
7428 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
7429 assert(PrettyArrayType && "Not an array type!");
7430
7431 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
7432
7433 // int x[restrict 4] -> int *restrict
7435 PrettyArrayType->getIndexTypeQualifiers());
7436
7437 // int x[_Nullable] -> int * _Nullable
7438 if (auto Nullability = Ty->getNullability()) {
7439 Result = const_cast<ASTContext *>(this)->getAttributedType(
7441 }
7442 return Result;
7443}
7444
7446 return getBaseElementType(array->getElementType());
7447}
7448
7450 Qualifiers qs;
7451 while (true) {
7452 SplitQualType split = type.getSplitDesugaredType();
7453 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
7454 if (!array) break;
7455
7456 type = array->getElementType();
7458 }
7459
7460 return getQualifiedType(type, qs);
7461}
7462
7463/// getConstantArrayElementCount - Returns number of constant array elements.
7464uint64_t
7466 uint64_t ElementCount = 1;
7467 do {
7468 ElementCount *= CA->getZExtSize();
7469 CA = dyn_cast_or_null<ConstantArrayType>(
7471 } while (CA);
7472 return ElementCount;
7473}
7474
7476 const ArrayInitLoopExpr *AILE) const {
7477 if (!AILE)
7478 return 0;
7479
7480 uint64_t ElementCount = 1;
7481
7482 do {
7483 ElementCount *= AILE->getArraySize().getZExtValue();
7484 AILE = dyn_cast<ArrayInitLoopExpr>(AILE->getSubExpr());
7485 } while (AILE);
7486
7487 return ElementCount;
7488}
7489
7490/// getFloatingRank - Return a relative rank for floating point types.
7491/// This routine will assert if passed a built-in type that isn't a float.
7493 if (const auto *CT = T->getAs<ComplexType>())
7494 return getFloatingRank(CT->getElementType());
7495
7496 switch (T->castAs<BuiltinType>()->getKind()) {
7497 default: llvm_unreachable("getFloatingRank(): not a floating type");
7498 case BuiltinType::Float16: return Float16Rank;
7499 case BuiltinType::Half: return HalfRank;
7500 case BuiltinType::Float: return FloatRank;
7501 case BuiltinType::Double: return DoubleRank;
7502 case BuiltinType::LongDouble: return LongDoubleRank;
7503 case BuiltinType::Float128: return Float128Rank;
7504 case BuiltinType::BFloat16: return BFloat16Rank;
7505 case BuiltinType::Ibm128: return Ibm128Rank;
7506 }
7507}
7508
7509/// getFloatingTypeOrder - Compare the rank of the two specified floating
7510/// point types, ignoring the domain of the type (i.e. 'double' ==
7511/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
7512/// LHS < RHS, return -1.
7514 FloatingRank LHSR = getFloatingRank(LHS);
7515 FloatingRank RHSR = getFloatingRank(RHS);
7516
7517 if (LHSR == RHSR)
7518 return 0;
7519 if (LHSR > RHSR)
7520 return 1;
7521 return -1;
7522}
7523
7526 return 0;
7527 return getFloatingTypeOrder(LHS, RHS);
7528}
7529
7530/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
7531/// routine will assert if passed a built-in type that isn't an integer or enum,
7532/// or if it is not canonicalized.
7533unsigned ASTContext::getIntegerRank(const Type *T) const {
7534 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
7535
7536 // Results in this 'losing' to any type of the same size, but winning if
7537 // larger.
7538 if (const auto *EIT = dyn_cast<BitIntType>(T))
7539 return 0 + (EIT->getNumBits() << 3);
7540
7541 switch (cast<BuiltinType>(T)->getKind()) {
7542 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
7543 case BuiltinType::Bool:
7544 return 1 + (getIntWidth(BoolTy) << 3);
7545 case BuiltinType::Char_S:
7546 case BuiltinType::Char_U:
7547 case BuiltinType::SChar:
7548 case BuiltinType::UChar:
7549 return 2 + (getIntWidth(CharTy) << 3);
7550 case BuiltinType::Short:
7551 case BuiltinType::UShort:
7552 return 3 + (getIntWidth(ShortTy) << 3);
7553 case BuiltinType::Int:
7554 case BuiltinType::UInt:
7555 return 4 + (getIntWidth(IntTy) << 3);
7556 case BuiltinType::Long:
7557 case BuiltinType::ULong:
7558 return 5 + (getIntWidth(LongTy) << 3);
7559 case BuiltinType::LongLong:
7560 case BuiltinType::ULongLong:
7561 return 6 + (getIntWidth(LongLongTy) << 3);
7562 case BuiltinType::Int128:
7563 case BuiltinType::UInt128:
7564 return 7 + (getIntWidth(Int128Ty) << 3);
7565
7566 // "The ranks of char8_t, char16_t, char32_t, and wchar_t equal the ranks of
7567 // their underlying types" [c++20 conv.rank]
7568 case BuiltinType::Char8:
7569 return getIntegerRank(UnsignedCharTy.getTypePtr());
7570 case BuiltinType::Char16:
7571 return getIntegerRank(
7572 getFromTargetType(Target->getChar16Type()).getTypePtr());
7573 case BuiltinType::Char32:
7574 return getIntegerRank(
7575 getFromTargetType(Target->getChar32Type()).getTypePtr());
7576 case BuiltinType::WChar_S:
7577 case BuiltinType::WChar_U:
7578 return getIntegerRank(
7579 getFromTargetType(Target->getWCharType()).getTypePtr());
7580 }
7581}
7582
7583/// Whether this is a promotable bitfield reference according
7584/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
7585///
7586/// \returns the type this bit-field will promote to, or NULL if no
7587/// promotion occurs.
7589 if (E->isTypeDependent() || E->isValueDependent())
7590 return {};
7591
7592 // C++ [conv.prom]p5:
7593 // If the bit-field has an enumerated type, it is treated as any other
7594 // value of that type for promotion purposes.
7596 return {};
7597
7598 // FIXME: We should not do this unless E->refersToBitField() is true. This
7599 // matters in C where getSourceBitField() will find bit-fields for various
7600 // cases where the source expression is not a bit-field designator.
7601
7602 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
7603 if (!Field)
7604 return {};
7605
7606 QualType FT = Field->getType();
7607
7608 uint64_t BitWidth = Field->getBitWidthValue(*this);
7609 uint64_t IntSize = getTypeSize(IntTy);
7610 // C++ [conv.prom]p5:
7611 // A prvalue for an integral bit-field can be converted to a prvalue of type
7612 // int if int can represent all the values of the bit-field; otherwise, it
7613 // can be converted to unsigned int if unsigned int can represent all the
7614 // values of the bit-field. If the bit-field is larger yet, no integral
7615 // promotion applies to it.
7616 // C11 6.3.1.1/2:
7617 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
7618 // If an int can represent all values of the original type (as restricted by
7619 // the width, for a bit-field), the value is converted to an int; otherwise,
7620 // it is converted to an unsigned int.
7621 //
7622 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
7623 // We perform that promotion here to match GCC and C++.
7624 // FIXME: C does not permit promotion of an enum bit-field whose rank is
7625 // greater than that of 'int'. We perform that promotion to match GCC.
7626 //
7627 // C23 6.3.1.1p2:
7628 // The value from a bit-field of a bit-precise integer type is converted to
7629 // the corresponding bit-precise integer type. (The rest is the same as in
7630 // C11.)
7631 if (QualType QT = Field->getType(); QT->isBitIntType())
7632 return QT;
7633
7634 if (BitWidth < IntSize)
7635 return IntTy;
7636
7637 if (BitWidth == IntSize)
7638 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
7639
7640 // Bit-fields wider than int are not subject to promotions, and therefore act
7641 // like the base type. GCC has some weird bugs in this area that we
7642 // deliberately do not follow (GCC follows a pre-standard resolution to
7643 // C's DR315 which treats bit-width as being part of the type, and this leaks
7644 // into their semantics in some cases).
7645 return {};
7646}
7647
7648/// getPromotedIntegerType - Returns the type that Promotable will
7649/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
7650/// integer type.
7652 assert(!Promotable.isNull());
7653 assert(isPromotableIntegerType(Promotable));
7654 if (const auto *ET = Promotable->getAs<EnumType>())
7655 return ET->getDecl()->getPromotionType();
7656
7657 if (const auto *BT = Promotable->getAs<BuiltinType>()) {
7658 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
7659 // (3.9.1) can be converted to a prvalue of the first of the following
7660 // types that can represent all the values of its underlying type:
7661 // int, unsigned int, long int, unsigned long int, long long int, or
7662 // unsigned long long int [...]
7663 // FIXME: Is there some better way to compute this?
7664 if (BT->getKind() == BuiltinType::WChar_S ||
7665 BT->getKind() == BuiltinType::WChar_U ||
7666 BT->getKind() == BuiltinType::Char8 ||
7667 BT->getKind() == BuiltinType::Char16 ||
7668 BT->getKind() == BuiltinType::Char32) {
7669 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
7670 uint64_t FromSize = getTypeSize(BT);
7671 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
7673 for (const auto &PT : PromoteTypes) {
7674 uint64_t ToSize = getTypeSize(PT);
7675 if (FromSize < ToSize ||
7676 (FromSize == ToSize && FromIsSigned == PT->isSignedIntegerType()))
7677 return PT;
7678 }
7679 llvm_unreachable("char type should fit into long long");
7680 }
7681 }
7682
7683 // At this point, we should have a signed or unsigned integer type.
7684 if (Promotable->isSignedIntegerType())
7685 return IntTy;
7686 uint64_t PromotableSize = getIntWidth(Promotable);
7687 uint64_t IntSize = getIntWidth(IntTy);
7688 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
7689 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
7690}
7691
7692/// Recurses in pointer/array types until it finds an objc retainable
7693/// type and returns its ownership.
7695 while (!T.isNull()) {
7696 if (T.getObjCLifetime() != Qualifiers::OCL_None)
7697 return T.getObjCLifetime();
7698 if (T->isArrayType())
7700 else if (const auto *PT = T->getAs<PointerType>())
7701 T = PT->getPointeeType();
7702 else if (const auto *RT = T->getAs<ReferenceType>())
7703 T = RT->getPointeeType();
7704 else
7705 break;
7706 }
7707
7708 return Qualifiers::OCL_None;
7709}
7710
7711static const Type *getIntegerTypeForEnum(const EnumType *ET) {
7712 // Incomplete enum types are not treated as integer types.
7713 // FIXME: In C++, enum types are never integer types.
7714 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
7715 return ET->getDecl()->getIntegerType().getTypePtr();
7716 return nullptr;
7717}
7718
7719/// getIntegerTypeOrder - Returns the highest ranked integer type:
7720/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
7721/// LHS < RHS, return -1.
7723 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
7724 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
7725
7726 // Unwrap enums to their underlying type.
7727 if (const auto *ET = dyn_cast<EnumType>(LHSC))
7728 LHSC = getIntegerTypeForEnum(ET);
7729 if (const auto *ET = dyn_cast<EnumType>(RHSC))
7730 RHSC = getIntegerTypeForEnum(ET);
7731
7732 if (LHSC == RHSC) return 0;
7733
7734 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
7735 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
7736
7737 unsigned LHSRank = getIntegerRank(LHSC);
7738 unsigned RHSRank = getIntegerRank(RHSC);
7739
7740 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
7741 if (LHSRank == RHSRank) return 0;
7742 return LHSRank > RHSRank ? 1 : -1;
7743 }
7744
7745 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
7746 if (LHSUnsigned) {
7747 // If the unsigned [LHS] type is larger, return it.
7748 if (LHSRank >= RHSRank)
7749 return 1;
7750
7751 // If the signed type can represent all values of the unsigned type, it
7752 // wins. Because we are dealing with 2's complement and types that are
7753 // powers of two larger than each other, this is always safe.
7754 return -1;
7755 }
7756
7757 // If the unsigned [RHS] type is larger, return it.
7758 if (RHSRank >= LHSRank)
7759 return -1;
7760
7761 // If the signed type can represent all values of the unsigned type, it
7762 // wins. Because we are dealing with 2's complement and types that are
7763 // powers of two larger than each other, this is always safe.
7764 return 1;
7765}
7766
7768 if (CFConstantStringTypeDecl)
7769 return CFConstantStringTypeDecl;
7770
7771 assert(!CFConstantStringTagDecl &&
7772 "tag and typedef should be initialized together");
7773 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
7774 CFConstantStringTagDecl->startDefinition();
7775
7776 struct {
7777 QualType Type;
7778 const char *Name;
7779 } Fields[5];
7780 unsigned Count = 0;
7781
7782 /// Objective-C ABI
7783 ///
7784 /// typedef struct __NSConstantString_tag {
7785 /// const int *isa;
7786 /// int flags;
7787 /// const char *str;
7788 /// long length;
7789 /// } __NSConstantString;
7790 ///
7791 /// Swift ABI (4.1, 4.2)
7792 ///
7793 /// typedef struct __NSConstantString_tag {
7794 /// uintptr_t _cfisa;
7795 /// uintptr_t _swift_rc;
7796 /// _Atomic(uint64_t) _cfinfoa;
7797 /// const char *_ptr;
7798 /// uint32_t _length;
7799 /// } __NSConstantString;
7800 ///
7801 /// Swift ABI (5.0)
7802 ///
7803 /// typedef struct __NSConstantString_tag {
7804 /// uintptr_t _cfisa;
7805 /// uintptr_t _swift_rc;
7806 /// _Atomic(uint64_t) _cfinfoa;
7807 /// const char *_ptr;
7808 /// uintptr_t _length;
7809 /// } __NSConstantString;
7810
7811 const auto CFRuntime = getLangOpts().CFRuntime;
7812 if (static_cast<unsigned>(CFRuntime) <
7813 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
7814 Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
7815 Fields[Count++] = { IntTy, "flags" };
7816 Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
7817 Fields[Count++] = { LongTy, "length" };
7818 } else {
7819 Fields[Count++] = { getUIntPtrType(), "_cfisa" };
7820 Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
7821 Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
7822 Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
7825 Fields[Count++] = { IntTy, "_ptr" };
7826 else
7827 Fields[Count++] = { getUIntPtrType(), "_ptr" };
7828 }
7829
7830 // Create fields
7831 for (unsigned i = 0; i < Count; ++i) {
7832 FieldDecl *Field =
7833 FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
7834 SourceLocation(), &Idents.get(Fields[i].Name),
7835 Fields[i].Type, /*TInfo=*/nullptr,
7836 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
7837 Field->setAccess(AS_public);
7838 CFConstantStringTagDecl->addDecl(Field);
7839 }
7840
7841 CFConstantStringTagDecl->completeDefinition();
7842 // This type is designed to be compatible with NSConstantString, but cannot
7843 // use the same name, since NSConstantString is an interface.
7844 auto tagType = getTagDeclType(CFConstantStringTagDecl);
7845 CFConstantStringTypeDecl =
7846 buildImplicitTypedef(tagType, "__NSConstantString");
7847
7848 return CFConstantStringTypeDecl;
7849}
7850
7852 if (!CFConstantStringTagDecl)
7853 getCFConstantStringDecl(); // Build the tag and the typedef.
7854 return CFConstantStringTagDecl;
7855}
7856
7857// getCFConstantStringType - Return the type used for constant CFStrings.
7860}
7861
7863 if (ObjCSuperType.isNull()) {
7864 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
7865 getTranslationUnitDecl()->addDecl(ObjCSuperTypeDecl);
7866 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
7867 }
7868 return ObjCSuperType;
7869}
7870
7872 const auto *TD = T->castAs<TypedefType>();
7873 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
7874 const auto *TagType =
7875 CFConstantStringTypeDecl->getUnderlyingType()->castAs<RecordType>();
7876 CFConstantStringTagDecl = TagType->getDecl();
7877}
7878
7880 if (BlockDescriptorType)
7881 return getTagDeclType(BlockDescriptorType);
7882
7883 RecordDecl *RD;
7884 // FIXME: Needs the FlagAppleBlock bit.
7885 RD = buildImplicitRecord("__block_descriptor");
7886 RD->startDefinition();
7887
7888 QualType FieldTypes[] = {
7891 };
7892
7893 static const char *const FieldNames[] = {
7894 "reserved",
7895 "Size"
7896 };
7897
7898 for (size_t i = 0; i < 2; ++i) {
7900 *this, RD, SourceLocation(), SourceLocation(),
7901 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
7902 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
7903 Field->setAccess(AS_public);
7904 RD->addDecl(Field);
7905 }
7906
7907 RD->completeDefinition();
7908
7909 BlockDescriptorType = RD;
7910
7911 return getTagDeclType(BlockDescriptorType);
7912}
7913
7915 if (BlockDescriptorExtendedType)
7916 return getTagDeclType(BlockDescriptorExtendedType);
7917
7918 RecordDecl *RD;
7919 // FIXME: Needs the FlagAppleBlock bit.
7920 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
7921 RD->startDefinition();
7922
7923 QualType FieldTypes[] = {
7928 };
7929
7930 static const char *const FieldNames[] = {
7931 "reserved",
7932 "Size",
7933 "CopyFuncPtr",
7934 "DestroyFuncPtr"
7935 };
7936
7937 for (size_t i = 0; i < 4; ++i) {
7939 *this, RD, SourceLocation(), SourceLocation(),
7940 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
7941 /*BitWidth=*/nullptr,
7942 /*Mutable=*/false, ICIS_NoInit);
7943 Field->setAccess(AS_public);
7944 RD->addDecl(Field);
7945 }
7946
7947 RD->completeDefinition();
7948
7949 BlockDescriptorExtendedType = RD;
7950 return getTagDeclType(BlockDescriptorExtendedType);
7951}
7952
7954 const auto *BT = dyn_cast<BuiltinType>(T);
7955
7956 if (!BT) {
7957 if (isa<PipeType>(T))
7958 return OCLTK_Pipe;
7959
7960 return OCLTK_Default;
7961 }
7962
7963 switch (BT->getKind()) {
7964#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7965 case BuiltinType::Id: \
7966 return OCLTK_Image;
7967#include "clang/Basic/OpenCLImageTypes.def"
7968
7969 case BuiltinType::OCLClkEvent:
7970 return OCLTK_ClkEvent;
7971
7972 case BuiltinType::OCLEvent:
7973 return OCLTK_Event;
7974
7975 case BuiltinType::OCLQueue:
7976 return OCLTK_Queue;
7977
7978 case BuiltinType::OCLReserveID:
7979 return OCLTK_ReserveID;
7980
7981 case BuiltinType::OCLSampler:
7982 return OCLTK_Sampler;
7983
7984 default:
7985 return OCLTK_Default;
7986 }
7987}
7988
7990 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
7991}
7992
7993/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
7994/// requires copy/dispose. Note that this must match the logic
7995/// in buildByrefHelpers.
7997 const VarDecl *D) {
7998 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
7999 const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
8000 if (!copyExpr && record->hasTrivialDestructor()) return false;
8001
8002 return true;
8003 }
8004
8005 // The block needs copy/destroy helpers if Ty is non-trivial to destructively
8006 // move or destroy.
8008 return true;
8009
8010 if (!Ty->isObjCRetainableType()) return false;
8011
8012 Qualifiers qs = Ty.getQualifiers();
8013
8014 // If we have lifetime, that dominates.
8015 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
8016 switch (lifetime) {
8017 case Qualifiers::OCL_None: llvm_unreachable("impossible");
8018
8019 // These are just bits as far as the runtime is concerned.
8022 return false;
8023
8024 // These cases should have been taken care of when checking the type's
8025 // non-triviality.
8028 llvm_unreachable("impossible");
8029 }
8030 llvm_unreachable("fell out of lifetime switch!");
8031 }
8032 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
8034}
8035
8037 Qualifiers::ObjCLifetime &LifeTime,
8038 bool &HasByrefExtendedLayout) const {
8039 if (!getLangOpts().ObjC ||
8040 getLangOpts().getGC() != LangOptions::NonGC)
8041 return false;
8042
8043 HasByrefExtendedLayout = false;
8044 if (Ty->isRecordType()) {
8045 HasByrefExtendedLayout = true;
8046 LifeTime = Qualifiers::OCL_None;
8047 } else if ((LifeTime = Ty.getObjCLifetime())) {
8048 // Honor the ARC qualifiers.
8049 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
8050 // The MRR rule.
8052 } else {
8053 LifeTime = Qualifiers::OCL_None;
8054 }
8055 return true;
8056}
8057
8059 assert(Target && "Expected target to be initialized");
8060 const llvm::Triple &T = Target->getTriple();
8061 // Windows is LLP64 rather than LP64
8062 if (T.isOSWindows() && T.isArch64Bit())
8063 return UnsignedLongLongTy;
8064 return UnsignedLongTy;
8065}
8066
8068 assert(Target && "Expected target to be initialized");
8069 const llvm::Triple &T = Target->getTriple();
8070 // Windows is LLP64 rather than LP64
8071 if (T.isOSWindows() && T.isArch64Bit())
8072 return LongLongTy;
8073 return LongTy;
8074}
8075
8077 if (!ObjCInstanceTypeDecl)
8078 ObjCInstanceTypeDecl =
8079 buildImplicitTypedef(getObjCIdType(), "instancetype");
8080 return ObjCInstanceTypeDecl;
8081}
8082
8083// This returns true if a type has been typedefed to BOOL:
8084// typedef <type> BOOL;
8086 if (const auto *TT = dyn_cast<TypedefType>(T))
8087 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
8088 return II->isStr("BOOL");
8089
8090 return false;
8091}
8092
8093/// getObjCEncodingTypeSize returns size of type for objective-c encoding
8094/// purpose.
8096 if (!type->isIncompleteArrayType() && type->isIncompleteType())
8097 return CharUnits::Zero();
8098
8100
8101 // Make all integer and enum types at least as large as an int
8102 if (sz.isPositive() && type->isIntegralOrEnumerationType())
8103 sz = std::max(sz, getTypeSizeInChars(IntTy));
8104 // Treat arrays as pointers, since that's how they're passed in.
8105 else if (type->isArrayType())
8107 return sz;
8108}
8109
8111 return getTargetInfo().getCXXABI().isMicrosoft() &&
8112 VD->isStaticDataMember() &&
8114 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
8115}
8116
8119 if (!VD->isInline())
8121
8122 // In almost all cases, it's a weak definition.
8123 auto *First = VD->getFirstDecl();
8124 if (First->isInlineSpecified() || !First->isStaticDataMember())
8126
8127 // If there's a file-context declaration in this translation unit, it's a
8128 // non-discardable definition.
8129 for (auto *D : VD->redecls())
8131 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
8133
8134 // If we've not seen one yet, we don't know.
8136}
8137
8138static std::string charUnitsToString(const CharUnits &CU) {
8139 return llvm::itostr(CU.getQuantity());
8140}
8141
8142/// getObjCEncodingForBlock - Return the encoded type for this block
8143/// declaration.
8145 std::string S;
8146
8147 const BlockDecl *Decl = Expr->getBlockDecl();
8148 QualType BlockTy =
8150 QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType();
8151 // Encode result type.
8152 if (getLangOpts().EncodeExtendedBlockSig)
8154 true /*Extended*/);
8155 else
8156 getObjCEncodingForType(BlockReturnTy, S);
8157 // Compute size of all parameters.
8158 // Start with computing size of a pointer in number of bytes.
8159 // FIXME: There might(should) be a better way of doing this computation!
8161 CharUnits ParmOffset = PtrSize;
8162 for (auto *PI : Decl->parameters()) {
8163 QualType PType = PI->getType();
8165 if (sz.isZero())
8166 continue;
8167 assert(sz.isPositive() && "BlockExpr - Incomplete param type");
8168 ParmOffset += sz;
8169 }
8170 // Size of the argument frame
8171 S += charUnitsToString(ParmOffset);
8172 // Block pointer and offset.
8173 S += "@?0";
8174
8175 // Argument types.
8176 ParmOffset = PtrSize;
8177 for (auto *PVDecl : Decl->parameters()) {
8178 QualType PType = PVDecl->getOriginalType();
8179 if (const auto *AT =
8180 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8181 // Use array's original type only if it has known number of
8182 // elements.
8183 if (!isa<ConstantArrayType>(AT))
8184 PType = PVDecl->getType();
8185 } else if (PType->isFunctionType())
8186 PType = PVDecl->getType();
8187 if (getLangOpts().EncodeExtendedBlockSig)
8189 S, true /*Extended*/);
8190 else
8191 getObjCEncodingForType(PType, S);
8192 S += charUnitsToString(ParmOffset);
8193 ParmOffset += getObjCEncodingTypeSize(PType);
8194 }
8195
8196 return S;
8197}
8198
8199std::string
8201 std::string S;
8202 // Encode result type.
8203 getObjCEncodingForType(Decl->getReturnType(), S);
8204 CharUnits ParmOffset;
8205 // Compute size of all parameters.
8206 for (auto *PI : Decl->parameters()) {
8207 QualType PType = PI->getType();
8209 if (sz.isZero())
8210 continue;
8211
8212 assert(sz.isPositive() &&
8213 "getObjCEncodingForFunctionDecl - Incomplete param type");
8214 ParmOffset += sz;
8215 }
8216 S += charUnitsToString(ParmOffset);
8217 ParmOffset = CharUnits::Zero();
8218
8219 // Argument types.
8220 for (auto *PVDecl : Decl->parameters()) {
8221 QualType PType = PVDecl->getOriginalType();
8222 if (const auto *AT =
8223 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8224 // Use array's original type only if it has known number of
8225 // elements.
8226 if (!isa<ConstantArrayType>(AT))
8227 PType = PVDecl->getType();
8228 } else if (PType->isFunctionType())
8229 PType = PVDecl->getType();
8230 getObjCEncodingForType(PType, S);
8231 S += charUnitsToString(ParmOffset);
8232 ParmOffset += getObjCEncodingTypeSize(PType);
8233 }
8234
8235 return S;
8236}
8237
8238/// getObjCEncodingForMethodParameter - Return the encoded type for a single
8239/// method parameter or return type. If Extended, include class names and
8240/// block object types.
8242 QualType T, std::string& S,
8243 bool Extended) const {
8244 // Encode type qualifier, 'in', 'inout', etc. for the parameter.
8246 // Encode parameter type.
8247 ObjCEncOptions Options = ObjCEncOptions()
8248 .setExpandPointedToStructures()
8249 .setExpandStructures()
8250 .setIsOutermostType();
8251 if (Extended)
8252 Options.setEncodeBlockParameters().setEncodeClassNames();
8253 getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr);
8254}
8255
8256/// getObjCEncodingForMethodDecl - Return the encoded type for this method
8257/// declaration.
8259 bool Extended) const {
8260 // FIXME: This is not very efficient.
8261 // Encode return type.
8262 std::string S;
8263 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
8264 Decl->getReturnType(), S, Extended);
8265 // Compute size of all parameters.
8266 // Start with computing size of a pointer in number of bytes.
8267 // FIXME: There might(should) be a better way of doing this computation!
8269 // The first two arguments (self and _cmd) are pointers; account for
8270 // their size.
8271 CharUnits ParmOffset = 2 * PtrSize;
8272 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
8273 E = Decl->sel_param_end(); PI != E; ++PI) {
8274 QualType PType = (*PI)->getType();
8276 if (sz.isZero())
8277 continue;
8278
8279 assert(sz.isPositive() &&
8280 "getObjCEncodingForMethodDecl - Incomplete param type");
8281 ParmOffset += sz;
8282 }
8283 S += charUnitsToString(ParmOffset);
8284 S += "@0:";
8285 S += charUnitsToString(PtrSize);
8286
8287 // Argument types.
8288 ParmOffset = 2 * PtrSize;
8289 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
8290 E = Decl->sel_param_end(); PI != E; ++PI) {
8291 const ParmVarDecl *PVDecl = *PI;
8292 QualType PType = PVDecl->getOriginalType();
8293 if (const auto *AT =
8294 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8295 // Use array's original type only if it has known number of
8296 // elements.
8297 if (!isa<ConstantArrayType>(AT))
8298 PType = PVDecl->getType();
8299 } else if (PType->isFunctionType())
8300 PType = PVDecl->getType();
8302 PType, S, Extended);
8303 S += charUnitsToString(ParmOffset);
8304 ParmOffset += getObjCEncodingTypeSize(PType);
8305 }
8306
8307 return S;
8308}
8309
8312 const ObjCPropertyDecl *PD,
8313 const Decl *Container) const {
8314 if (!Container)
8315 return nullptr;
8316 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
8317 for (auto *PID : CID->property_impls())
8318 if (PID->getPropertyDecl() == PD)
8319 return PID;
8320 } else {
8321 const auto *OID = cast<ObjCImplementationDecl>(Container);
8322 for (auto *PID : OID->property_impls())
8323 if (PID->getPropertyDecl() == PD)
8324 return PID;
8325 }
8326 return nullptr;
8327}
8328
8329/// getObjCEncodingForPropertyDecl - Return the encoded type for this
8330/// property declaration. If non-NULL, Container must be either an
8331/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
8332/// NULL when getting encodings for protocol properties.
8333/// Property attributes are stored as a comma-delimited C string. The simple
8334/// attributes readonly and bycopy are encoded as single characters. The
8335/// parametrized attributes, getter=name, setter=name, and ivar=name, are
8336/// encoded as single characters, followed by an identifier. Property types
8337/// are also encoded as a parametrized attribute. The characters used to encode
8338/// these attributes are defined by the following enumeration:
8339/// @code
8340/// enum PropertyAttributes {
8341/// kPropertyReadOnly = 'R', // property is read-only.
8342/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
8343/// kPropertyByref = '&', // property is a reference to the value last assigned
8344/// kPropertyDynamic = 'D', // property is dynamic
8345/// kPropertyGetter = 'G', // followed by getter selector name
8346/// kPropertySetter = 'S', // followed by setter selector name
8347/// kPropertyInstanceVariable = 'V' // followed by instance variable name
8348/// kPropertyType = 'T' // followed by old-style type encoding.
8349/// kPropertyWeak = 'W' // 'weak' property
8350/// kPropertyStrong = 'P' // property GC'able
8351/// kPropertyNonAtomic = 'N' // property non-atomic
8352/// kPropertyOptional = '?' // property optional
8353/// };
8354/// @endcode
8355std::string
8357 const Decl *Container) const {
8358 // Collect information from the property implementation decl(s).
8359 bool Dynamic = false;
8360 ObjCPropertyImplDecl *SynthesizePID = nullptr;
8361
8362 if (ObjCPropertyImplDecl *PropertyImpDecl =
8364 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
8365 Dynamic = true;
8366 else
8367 SynthesizePID = PropertyImpDecl;
8368 }
8369
8370 // FIXME: This is not very efficient.
8371 std::string S = "T";
8372
8373 // Encode result type.
8374 // GCC has some special rules regarding encoding of properties which
8375 // closely resembles encoding of ivars.
8377
8378 if (PD->isOptional())
8379 S += ",?";
8380
8381 if (PD->isReadOnly()) {
8382 S += ",R";
8384 S += ",C";
8386 S += ",&";
8388 S += ",W";
8389 } else {
8390 switch (PD->getSetterKind()) {
8391 case ObjCPropertyDecl::Assign: break;
8392 case ObjCPropertyDecl::Copy: S += ",C"; break;
8393 case ObjCPropertyDecl::Retain: S += ",&"; break;
8394 case ObjCPropertyDecl::Weak: S += ",W"; break;
8395 }
8396 }
8397
8398 // It really isn't clear at all what this means, since properties
8399 // are "dynamic by default".
8400 if (Dynamic)
8401 S += ",D";
8402
8404 S += ",N";
8405
8407 S += ",G";
8408 S += PD->getGetterName().getAsString();
8409 }
8410
8412 S += ",S";
8413 S += PD->getSetterName().getAsString();
8414 }
8415
8416 if (SynthesizePID) {
8417 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
8418 S += ",V";
8419 S += OID->getNameAsString();
8420 }
8421
8422 // FIXME: OBJCGC: weak & strong
8423 return S;
8424}
8425
8426/// getLegacyIntegralTypeEncoding -
8427/// Another legacy compatibility encoding: 32-bit longs are encoded as
8428/// 'l' or 'L' , but not always. For typedefs, we need to use
8429/// 'i' or 'I' instead if encoding a struct field, or a pointer!
8431 if (PointeeTy->getAs<TypedefType>()) {
8432 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
8433 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
8434 PointeeTy = UnsignedIntTy;
8435 else
8436 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
8437 PointeeTy = IntTy;
8438 }
8439 }
8440}
8441
8443 const FieldDecl *Field,
8444 QualType *NotEncodedT) const {
8445 // We follow the behavior of gcc, expanding structures which are
8446 // directly pointed to, and expanding embedded structures. Note that
8447 // these rules are sufficient to prevent recursive encoding of the
8448 // same type.
8449 getObjCEncodingForTypeImpl(T, S,
8450 ObjCEncOptions()
8451 .setExpandPointedToStructures()
8452 .setExpandStructures()
8453 .setIsOutermostType(),
8454 Field, NotEncodedT);
8455}
8456
8458 std::string& S) const {
8459 // Encode result type.
8460 // GCC has some special rules regarding encoding of properties which
8461 // closely resembles encoding of ivars.
8462 getObjCEncodingForTypeImpl(T, S,
8463 ObjCEncOptions()
8464 .setExpandPointedToStructures()
8465 .setExpandStructures()
8466 .setIsOutermostType()
8467 .setEncodingProperty(),
8468 /*Field=*/nullptr);
8469}
8470
8472 const BuiltinType *BT) {
8473 BuiltinType::Kind kind = BT->getKind();
8474 switch (kind) {
8475 case BuiltinType::Void: return 'v';
8476 case BuiltinType::Bool: return 'B';
8477 case BuiltinType::Char8:
8478 case BuiltinType::Char_U:
8479 case BuiltinType::UChar: return 'C';
8480 case BuiltinType::Char16:
8481 case BuiltinType::UShort: return 'S';
8482 case BuiltinType::Char32:
8483 case BuiltinType::UInt: return 'I';
8484 case BuiltinType::ULong:
8485 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
8486 case BuiltinType::UInt128: return 'T';
8487 case BuiltinType::ULongLong: return 'Q';
8488 case BuiltinType::Char_S:
8489 case BuiltinType::SChar: return 'c';
8490 case BuiltinType::Short: return 's';
8491 case BuiltinType::WChar_S:
8492 case BuiltinType::WChar_U:
8493 case BuiltinType::Int: return 'i';
8494 case BuiltinType::Long:
8495 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
8496 case BuiltinType::LongLong: return 'q';
8497 case BuiltinType::Int128: return 't';
8498 case BuiltinType::Float: return 'f';
8499 case BuiltinType::Double: return 'd';
8500 case BuiltinType::LongDouble: return 'D';
8501 case BuiltinType::NullPtr: return '*'; // like char*
8502
8503 case BuiltinType::BFloat16:
8504 case BuiltinType::Float16:
8505 case BuiltinType::Float128:
8506 case BuiltinType::Ibm128:
8507 case BuiltinType::Half:
8508 case BuiltinType::ShortAccum:
8509 case BuiltinType::Accum:
8510 case BuiltinType::LongAccum:
8511 case BuiltinType::UShortAccum:
8512 case BuiltinType::UAccum:
8513 case BuiltinType::ULongAccum:
8514 case BuiltinType::ShortFract:
8515 case BuiltinType::Fract:
8516 case BuiltinType::LongFract:
8517 case BuiltinType::UShortFract:
8518 case BuiltinType::UFract:
8519 case BuiltinType::ULongFract:
8520 case BuiltinType::SatShortAccum:
8521 case BuiltinType::SatAccum:
8522 case BuiltinType::SatLongAccum:
8523 case BuiltinType::SatUShortAccum:
8524 case BuiltinType::SatUAccum:
8525 case BuiltinType::SatULongAccum:
8526 case BuiltinType::SatShortFract:
8527 case BuiltinType::SatFract:
8528 case BuiltinType::SatLongFract:
8529 case BuiltinType::SatUShortFract:
8530 case BuiltinType::SatUFract:
8531 case BuiltinType::SatULongFract:
8532 // FIXME: potentially need @encodes for these!
8533 return ' ';
8534
8535#define SVE_TYPE(Name, Id, SingletonId) \
8536 case BuiltinType::Id:
8537#include "clang/Basic/AArch64SVEACLETypes.def"
8538#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
8539#include "clang/Basic/RISCVVTypes.def"
8540#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
8541#include "clang/Basic/WebAssemblyReferenceTypes.def"
8542#define AMDGPU_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
8543#include "clang/Basic/AMDGPUTypes.def"
8544 {
8545 DiagnosticsEngine &Diags = C->getDiagnostics();
8546 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
8547 "cannot yet @encode type %0");
8548 Diags.Report(DiagID) << BT->getName(C->getPrintingPolicy());
8549 return ' ';
8550 }
8551
8552 case BuiltinType::ObjCId:
8553 case BuiltinType::ObjCClass:
8554 case BuiltinType::ObjCSel:
8555 llvm_unreachable("@encoding ObjC primitive type");
8556
8557 // OpenCL and placeholder types don't need @encodings.
8558#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8559 case BuiltinType::Id:
8560#include "clang/Basic/OpenCLImageTypes.def"
8561#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
8562 case BuiltinType::Id:
8563#include "clang/Basic/OpenCLExtensionTypes.def"
8564 case BuiltinType::OCLEvent:
8565 case BuiltinType::OCLClkEvent:
8566 case BuiltinType::OCLQueue:
8567 case BuiltinType::OCLReserveID:
8568 case BuiltinType::OCLSampler:
8569 case BuiltinType::Dependent:
8570#define PPC_VECTOR_TYPE(Name, Id, Size) \
8571 case BuiltinType::Id:
8572#include "clang/Basic/PPCTypes.def"
8573#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
8574#include "clang/Basic/HLSLIntangibleTypes.def"
8575#define BUILTIN_TYPE(KIND, ID)
8576#define PLACEHOLDER_TYPE(KIND, ID) \
8577 case BuiltinType::KIND:
8578#include "clang/AST/BuiltinTypes.def"
8579 llvm_unreachable("invalid builtin type for @encode");
8580 }
8581 llvm_unreachable("invalid BuiltinType::Kind value");
8582}
8583
8584static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
8585 EnumDecl *Enum = ET->getDecl();
8586
8587 // The encoding of an non-fixed enum type is always 'i', regardless of size.
8588 if (!Enum->isFixed())
8589 return 'i';
8590
8591 // The encoding of a fixed enum type matches its fixed underlying type.
8592 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
8594}
8595
8596static void EncodeBitField(const ASTContext *Ctx, std::string& S,
8597 QualType T, const FieldDecl *FD) {
8598 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
8599 S += 'b';
8600 // The NeXT runtime encodes bit fields as b followed by the number of bits.
8601 // The GNU runtime requires more information; bitfields are encoded as b,
8602 // then the offset (in bits) of the first element, then the type of the
8603 // bitfield, then the size in bits. For example, in this structure:
8604 //
8605 // struct
8606 // {
8607 // int integer;
8608 // int flags:2;
8609 // };
8610 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
8611 // runtime, but b32i2 for the GNU runtime. The reason for this extra
8612 // information is not especially sensible, but we're stuck with it for
8613 // compatibility with GCC, although providing it breaks anything that
8614 // actually uses runtime introspection and wants to work on both runtimes...
8615 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
8616 uint64_t Offset;
8617
8618 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
8619 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr,
8620 IVD);
8621 } else {
8622 const RecordDecl *RD = FD->getParent();
8623 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
8624 Offset = RL.getFieldOffset(FD->getFieldIndex());
8625 }
8626
8627 S += llvm::utostr(Offset);
8628
8629 if (const auto *ET = T->getAs<EnumType>())
8630 S += ObjCEncodingForEnumType(Ctx, ET);
8631 else {
8632 const auto *BT = T->castAs<BuiltinType>();
8633 S += getObjCEncodingForPrimitiveType(Ctx, BT);
8634 }
8635 }
8636 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
8637}
8638
8639// Helper function for determining whether the encoded type string would include
8640// a template specialization type.
8642 bool VisitBasesAndFields) {
8644
8645 if (auto *PT = T->getAs<PointerType>())
8647 PT->getPointeeType().getTypePtr(), false);
8648
8649 auto *CXXRD = T->getAsCXXRecordDecl();
8650
8651 if (!CXXRD)
8652 return false;
8653
8654 if (isa<ClassTemplateSpecializationDecl>(CXXRD))
8655 return true;
8656
8657 if (!CXXRD->hasDefinition() || !VisitBasesAndFields)
8658 return false;
8659
8660 for (const auto &B : CXXRD->bases())
8661 if (hasTemplateSpecializationInEncodedString(B.getType().getTypePtr(),
8662 true))
8663 return true;
8664
8665 for (auto *FD : CXXRD->fields())
8666 if (hasTemplateSpecializationInEncodedString(FD->getType().getTypePtr(),
8667 true))
8668 return true;
8669
8670 return false;
8671}
8672
8673// FIXME: Use SmallString for accumulating string.
8674void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
8675 const ObjCEncOptions Options,
8676 const FieldDecl *FD,
8677 QualType *NotEncodedT) const {
8679 switch (CT->getTypeClass()) {
8680 case Type::Builtin:
8681 case Type::Enum:
8682 if (FD && FD->isBitField())
8683 return EncodeBitField(this, S, T, FD);
8684 if (const auto *BT = dyn_cast<BuiltinType>(CT))
8685 S += getObjCEncodingForPrimitiveType(this, BT);
8686 else
8687 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
8688 return;
8689
8690 case Type::Complex:
8691 S += 'j';
8692 getObjCEncodingForTypeImpl(T->castAs<ComplexType>()->getElementType(), S,
8693 ObjCEncOptions(),
8694 /*Field=*/nullptr);
8695 return;
8696
8697 case Type::Atomic:
8698 S += 'A';
8699 getObjCEncodingForTypeImpl(T->castAs<AtomicType>()->getValueType(), S,
8700 ObjCEncOptions(),
8701 /*Field=*/nullptr);
8702 return;
8703
8704 // encoding for pointer or reference types.
8705 case Type::Pointer:
8706 case Type::LValueReference:
8707 case Type::RValueReference: {
8708 QualType PointeeTy;
8709 if (isa<PointerType>(CT)) {
8710 const auto *PT = T->castAs<PointerType>();
8711 if (PT->isObjCSelType()) {
8712 S += ':';
8713 return;
8714 }
8715 PointeeTy = PT->getPointeeType();
8716 } else {
8717 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
8718 }
8719
8720 bool isReadOnly = false;
8721 // For historical/compatibility reasons, the read-only qualifier of the
8722 // pointee gets emitted _before_ the '^'. The read-only qualifier of
8723 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
8724 // Also, do not emit the 'r' for anything but the outermost type!
8725 if (T->getAs<TypedefType>()) {
8726 if (Options.IsOutermostType() && T.isConstQualified()) {
8727 isReadOnly = true;
8728 S += 'r';
8729 }
8730 } else if (Options.IsOutermostType()) {
8731 QualType P = PointeeTy;
8732 while (auto PT = P->getAs<PointerType>())
8733 P = PT->getPointeeType();
8734 if (P.isConstQualified()) {
8735 isReadOnly = true;
8736 S += 'r';
8737 }
8738 }
8739 if (isReadOnly) {
8740 // Another legacy compatibility encoding. Some ObjC qualifier and type
8741 // combinations need to be rearranged.
8742 // Rewrite "in const" from "nr" to "rn"
8743 if (StringRef(S).ends_with("nr"))
8744 S.replace(S.end()-2, S.end(), "rn");
8745 }
8746
8747 if (PointeeTy->isCharType()) {
8748 // char pointer types should be encoded as '*' unless it is a
8749 // type that has been typedef'd to 'BOOL'.
8750 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
8751 S += '*';
8752 return;
8753 }
8754 } else if (const auto *RTy = PointeeTy->getAs<RecordType>()) {
8755 // GCC binary compat: Need to convert "struct objc_class *" to "#".
8756 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
8757 S += '#';
8758 return;
8759 }
8760 // GCC binary compat: Need to convert "struct objc_object *" to "@".
8761 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
8762 S += '@';
8763 return;
8764 }
8765 // If the encoded string for the class includes template names, just emit
8766 // "^v" for pointers to the class.
8767 if (getLangOpts().CPlusPlus &&
8768 (!getLangOpts().EncodeCXXClassTemplateSpec &&
8770 RTy, Options.ExpandPointedToStructures()))) {
8771 S += "^v";
8772 return;
8773 }
8774 // fall through...
8775 }
8776 S += '^';
8778
8779 ObjCEncOptions NewOptions;
8780 if (Options.ExpandPointedToStructures())
8781 NewOptions.setExpandStructures();
8782 getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions,
8783 /*Field=*/nullptr, NotEncodedT);
8784 return;
8785 }
8786
8787 case Type::ConstantArray:
8788 case Type::IncompleteArray:
8789 case Type::VariableArray: {
8790 const auto *AT = cast<ArrayType>(CT);
8791
8792 if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) {
8793 // Incomplete arrays are encoded as a pointer to the array element.
8794 S += '^';
8795
8796 getObjCEncodingForTypeImpl(
8797 AT->getElementType(), S,
8798 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD);
8799 } else {
8800 S += '[';
8801
8802 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
8803 S += llvm::utostr(CAT->getZExtSize());
8804 else {
8805 //Variable length arrays are encoded as a regular array with 0 elements.
8806 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
8807 "Unknown array type!");
8808 S += '0';
8809 }
8810
8811 getObjCEncodingForTypeImpl(
8812 AT->getElementType(), S,
8813 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD,
8814 NotEncodedT);
8815 S += ']';
8816 }
8817 return;
8818 }
8819
8820 case Type::FunctionNoProto:
8821 case Type::FunctionProto:
8822 S += '?';
8823 return;
8824
8825 case Type::Record: {
8826 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
8827 S += RDecl->isUnion() ? '(' : '{';
8828 // Anonymous structures print as '?'
8829 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
8830 S += II->getName();
8831 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
8832 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
8833 llvm::raw_string_ostream OS(S);
8834 printTemplateArgumentList(OS, TemplateArgs.asArray(),
8836 }
8837 } else {
8838 S += '?';
8839 }
8840 if (Options.ExpandStructures()) {
8841 S += '=';
8842 if (!RDecl->isUnion()) {
8843 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
8844 } else {
8845 for (const auto *Field : RDecl->fields()) {
8846 if (FD) {
8847 S += '"';
8848 S += Field->getNameAsString();
8849 S += '"';
8850 }
8851
8852 // Special case bit-fields.
8853 if (Field->isBitField()) {
8854 getObjCEncodingForTypeImpl(Field->getType(), S,
8855 ObjCEncOptions().setExpandStructures(),
8856 Field);
8857 } else {
8858 QualType qt = Field->getType();
8860 getObjCEncodingForTypeImpl(
8861 qt, S,
8862 ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
8863 NotEncodedT);
8864 }
8865 }
8866 }
8867 }
8868 S += RDecl->isUnion() ? ')' : '}';
8869 return;
8870 }
8871
8872 case Type::BlockPointer: {
8873 const auto *BT = T->castAs<BlockPointerType>();
8874 S += "@?"; // Unlike a pointer-to-function, which is "^?".
8875 if (Options.EncodeBlockParameters()) {
8876 const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
8877
8878 S += '<';
8879 // Block return type
8880 getObjCEncodingForTypeImpl(FT->getReturnType(), S,
8881 Options.forComponentType(), FD, NotEncodedT);
8882 // Block self
8883 S += "@?";
8884 // Block parameters
8885 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
8886 for (const auto &I : FPT->param_types())
8887 getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD,
8888 NotEncodedT);
8889 }
8890 S += '>';
8891 }
8892 return;
8893 }
8894
8895 case Type::ObjCObject: {
8896 // hack to match legacy encoding of *id and *Class
8898 if (Ty->isObjCIdType()) {
8899 S += "{objc_object=}";
8900 return;
8901 }
8902 else if (Ty->isObjCClassType()) {
8903 S += "{objc_class=}";
8904 return;
8905 }
8906 // TODO: Double check to make sure this intentionally falls through.
8907 [[fallthrough]];
8908 }
8909
8910 case Type::ObjCInterface: {
8911 // Ignore protocol qualifiers when mangling at this level.
8912 // @encode(class_name)
8913 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
8914 S += '{';
8915 S += OI->getObjCRuntimeNameAsString();
8916 if (Options.ExpandStructures()) {
8917 S += '=';
8919 DeepCollectObjCIvars(OI, true, Ivars);
8920 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
8921 const FieldDecl *Field = Ivars[i];
8922 if (Field->isBitField())
8923 getObjCEncodingForTypeImpl(Field->getType(), S,
8924 ObjCEncOptions().setExpandStructures(),
8925 Field);
8926 else
8927 getObjCEncodingForTypeImpl(Field->getType(), S,
8928 ObjCEncOptions().setExpandStructures(), FD,
8929 NotEncodedT);
8930 }
8931 }
8932 S += '}';
8933 return;
8934 }
8935
8936 case Type::ObjCObjectPointer: {
8937 const auto *OPT = T->castAs<ObjCObjectPointerType>();
8938 if (OPT->isObjCIdType()) {
8939 S += '@';
8940 return;
8941 }
8942
8943 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
8944 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
8945 // Since this is a binary compatibility issue, need to consult with
8946 // runtime folks. Fortunately, this is a *very* obscure construct.
8947 S += '#';
8948 return;
8949 }
8950
8951 if (OPT->isObjCQualifiedIdType()) {
8952 getObjCEncodingForTypeImpl(
8953 getObjCIdType(), S,
8954 Options.keepingOnly(ObjCEncOptions()
8955 .setExpandPointedToStructures()
8956 .setExpandStructures()),
8957 FD);
8958 if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
8959 // Note that we do extended encoding of protocol qualifier list
8960 // Only when doing ivar or property encoding.
8961 S += '"';
8962 for (const auto *I : OPT->quals()) {
8963 S += '<';
8964 S += I->getObjCRuntimeNameAsString();
8965 S += '>';
8966 }
8967 S += '"';
8968 }
8969 return;
8970 }
8971
8972 S += '@';
8973 if (OPT->getInterfaceDecl() &&
8974 (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
8975 S += '"';
8976 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
8977 for (const auto *I : OPT->quals()) {
8978 S += '<';
8979 S += I->getObjCRuntimeNameAsString();
8980 S += '>';
8981 }
8982 S += '"';
8983 }
8984 return;
8985 }
8986
8987 // gcc just blithely ignores member pointers.
8988 // FIXME: we should do better than that. 'M' is available.
8989 case Type::MemberPointer:
8990 // This matches gcc's encoding, even though technically it is insufficient.
8991 //FIXME. We should do a better job than gcc.
8992 case Type::Vector:
8993 case Type::ExtVector:
8994 // Until we have a coherent encoding of these three types, issue warning.
8995 if (NotEncodedT)
8996 *NotEncodedT = T;
8997 return;
8998
8999 case Type::ConstantMatrix:
9000 if (NotEncodedT)
9001 *NotEncodedT = T;
9002 return;
9003
9004 case Type::BitInt:
9005 if (NotEncodedT)
9006 *NotEncodedT = T;
9007 return;
9008
9009 // We could see an undeduced auto type here during error recovery.
9010 // Just ignore it.
9011 case Type::Auto:
9012 case Type::DeducedTemplateSpecialization:
9013 return;
9014
9015 case Type::ArrayParameter:
9016 case Type::Pipe:
9017#define ABSTRACT_TYPE(KIND, BASE)
9018#define TYPE(KIND, BASE)
9019#define DEPENDENT_TYPE(KIND, BASE) \
9020 case Type::KIND:
9021#define NON_CANONICAL_TYPE(KIND, BASE) \
9022 case Type::KIND:
9023#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
9024 case Type::KIND:
9025#include "clang/AST/TypeNodes.inc"
9026 llvm_unreachable("@encode for dependent type!");
9027 }
9028 llvm_unreachable("bad type kind!");
9029}
9030
9031void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
9032 std::string &S,
9033 const FieldDecl *FD,
9034 bool includeVBases,
9035 QualType *NotEncodedT) const {
9036 assert(RDecl && "Expected non-null RecordDecl");
9037 assert(!RDecl->isUnion() && "Should not be called for unions");
9038 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
9039 return;
9040
9041 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
9042 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
9043 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
9044
9045 if (CXXRec) {
9046 for (const auto &BI : CXXRec->bases()) {
9047 if (!BI.isVirtual()) {
9048 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9049 if (base->isEmpty())
9050 continue;
9051 uint64_t offs = toBits(layout.getBaseClassOffset(base));
9052 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9053 std::make_pair(offs, base));
9054 }
9055 }
9056 }
9057
9058 for (FieldDecl *Field : RDecl->fields()) {
9059 if (!Field->isZeroLengthBitField(*this) && Field->isZeroSize(*this))
9060 continue;
9061 uint64_t offs = layout.getFieldOffset(Field->getFieldIndex());
9062 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9063 std::make_pair(offs, Field));
9064 }
9065
9066 if (CXXRec && includeVBases) {
9067 for (const auto &BI : CXXRec->vbases()) {
9068 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9069 if (base->isEmpty())
9070 continue;
9071 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
9072 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
9073 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
9074 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
9075 std::make_pair(offs, base));
9076 }
9077 }
9078
9079 CharUnits size;
9080 if (CXXRec) {
9081 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
9082 } else {
9083 size = layout.getSize();
9084 }
9085
9086#ifndef NDEBUG
9087 uint64_t CurOffs = 0;
9088#endif
9089 std::multimap<uint64_t, NamedDecl *>::iterator
9090 CurLayObj = FieldOrBaseOffsets.begin();
9091
9092 if (CXXRec && CXXRec->isDynamicClass() &&
9093 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
9094 if (FD) {
9095 S += "\"_vptr$";
9096 std::string recname = CXXRec->getNameAsString();
9097 if (recname.empty()) recname = "?";
9098 S += recname;
9099 S += '"';
9100 }
9101 S += "^^?";
9102#ifndef NDEBUG
9103 CurOffs += getTypeSize(VoidPtrTy);
9104#endif
9105 }
9106
9107 if (!RDecl->hasFlexibleArrayMember()) {
9108 // Mark the end of the structure.
9109 uint64_t offs = toBits(size);
9110 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9111 std::make_pair(offs, nullptr));
9112 }
9113
9114 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
9115#ifndef NDEBUG
9116 assert(CurOffs <= CurLayObj->first);
9117 if (CurOffs < CurLayObj->first) {
9118 uint64_t padding = CurLayObj->first - CurOffs;
9119 // FIXME: There doesn't seem to be a way to indicate in the encoding that
9120 // packing/alignment of members is different that normal, in which case
9121 // the encoding will be out-of-sync with the real layout.
9122 // If the runtime switches to just consider the size of types without
9123 // taking into account alignment, we could make padding explicit in the
9124 // encoding (e.g. using arrays of chars). The encoding strings would be
9125 // longer then though.
9126 CurOffs += padding;
9127 }
9128#endif
9129
9130 NamedDecl *dcl = CurLayObj->second;
9131 if (!dcl)
9132 break; // reached end of structure.
9133
9134 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
9135 // We expand the bases without their virtual bases since those are going
9136 // in the initial structure. Note that this differs from gcc which
9137 // expands virtual bases each time one is encountered in the hierarchy,
9138 // making the encoding type bigger than it really is.
9139 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
9140 NotEncodedT);
9141 assert(!base->isEmpty());
9142#ifndef NDEBUG
9143 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
9144#endif
9145 } else {
9146 const auto *field = cast<FieldDecl>(dcl);
9147 if (FD) {
9148 S += '"';
9149 S += field->getNameAsString();
9150 S += '"';
9151 }
9152
9153 if (field->isBitField()) {
9154 EncodeBitField(this, S, field->getType(), field);
9155#ifndef NDEBUG
9156 CurOffs += field->getBitWidthValue(*this);
9157#endif
9158 } else {
9159 QualType qt = field->getType();
9161 getObjCEncodingForTypeImpl(
9162 qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(),
9163 FD, NotEncodedT);
9164#ifndef NDEBUG
9165 CurOffs += getTypeSize(field->getType());
9166#endif
9167 }
9168 }
9169 }
9170}
9171
9173 std::string& S) const {
9174 if (QT & Decl::OBJC_TQ_In)
9175 S += 'n';
9176 if (QT & Decl::OBJC_TQ_Inout)
9177 S += 'N';
9178 if (QT & Decl::OBJC_TQ_Out)
9179 S += 'o';
9180 if (QT & Decl::OBJC_TQ_Bycopy)
9181 S += 'O';
9182 if (QT & Decl::OBJC_TQ_Byref)
9183 S += 'R';
9184 if (QT & Decl::OBJC_TQ_Oneway)
9185 S += 'V';
9186}
9187
9189 if (!ObjCIdDecl) {
9192 ObjCIdDecl = buildImplicitTypedef(T, "id");
9193 }
9194 return ObjCIdDecl;
9195}
9196
9198 if (!ObjCSelDecl) {
9200 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
9201 }
9202 return ObjCSelDecl;
9203}
9204
9206 if (!ObjCClassDecl) {
9209 ObjCClassDecl = buildImplicitTypedef(T, "Class");
9210 }
9211 return ObjCClassDecl;
9212}
9213
9215 if (!ObjCProtocolClassDecl) {
9216 ObjCProtocolClassDecl
9219 &Idents.get("Protocol"),
9220 /*typeParamList=*/nullptr,
9221 /*PrevDecl=*/nullptr,
9222 SourceLocation(), true);
9223 }
9224
9225 return ObjCProtocolClassDecl;
9226}
9227
9228//===----------------------------------------------------------------------===//
9229// __builtin_va_list Construction Functions
9230//===----------------------------------------------------------------------===//
9231
9233 StringRef Name) {
9234 // typedef char* __builtin[_ms]_va_list;
9235 QualType T = Context->getPointerType(Context->CharTy);
9236 return Context->buildImplicitTypedef(T, Name);
9237}
9238
9240 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
9241}
9242
9244 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
9245}
9246
9248 // typedef void* __builtin_va_list;
9249 QualType T = Context->getPointerType(Context->VoidTy);
9250 return Context->buildImplicitTypedef(T, "__builtin_va_list");
9251}
9252
9253static TypedefDecl *
9255 // struct __va_list
9256 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
9257 if (Context->getLangOpts().CPlusPlus) {
9258 // namespace std { struct __va_list {
9259 auto *NS = NamespaceDecl::Create(
9260 const_cast<ASTContext &>(*Context), Context->getTranslationUnitDecl(),
9261 /*Inline=*/false, SourceLocation(), SourceLocation(),
9262 &Context->Idents.get("std"),
9263 /*PrevDecl=*/nullptr, /*Nested=*/false);
9264 NS->setImplicit();
9265 VaListTagDecl->setDeclContext(NS);
9266 }
9267
9268 VaListTagDecl->startDefinition();
9269
9270 const size_t NumFields = 5;
9271 QualType FieldTypes[NumFields];
9272 const char *FieldNames[NumFields];
9273
9274 // void *__stack;
9275 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
9276 FieldNames[0] = "__stack";
9277
9278 // void *__gr_top;
9279 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
9280 FieldNames[1] = "__gr_top";
9281
9282 // void *__vr_top;
9283 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
9284 FieldNames[2] = "__vr_top";
9285
9286 // int __gr_offs;
9287 FieldTypes[3] = Context->IntTy;
9288 FieldNames[3] = "__gr_offs";
9289
9290 // int __vr_offs;
9291 FieldTypes[4] = Context->IntTy;
9292 FieldNames[4] = "__vr_offs";
9293
9294 // Create fields
9295 for (unsigned i = 0; i < NumFields; ++i) {
9296 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
9297 VaListTagDecl,
9300 &Context->Idents.get(FieldNames[i]),
9301 FieldTypes[i], /*TInfo=*/nullptr,
9302 /*BitWidth=*/nullptr,
9303 /*Mutable=*/false,
9304 ICIS_NoInit);
9305 Field->setAccess(AS_public);
9306 VaListTagDecl->addDecl(Field);
9307 }
9308 VaListTagDecl->completeDefinition();
9309 Context->VaListTagDecl = VaListTagDecl;
9310 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
9311
9312 // } __builtin_va_list;
9313 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
9314}
9315
9317 // typedef struct __va_list_tag {
9318 RecordDecl *VaListTagDecl;
9319
9320 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
9321 VaListTagDecl->startDefinition();
9322
9323 const size_t NumFields = 5;
9324 QualType FieldTypes[NumFields];
9325 const char *FieldNames[NumFields];
9326
9327 // unsigned char gpr;
9328 FieldTypes[0] = Context->UnsignedCharTy;
9329 FieldNames[0] = "gpr";
9330
9331 // unsigned char fpr;
9332 FieldTypes[1] = Context->UnsignedCharTy;
9333 FieldNames[1] = "fpr";
9334
9335 // unsigned short reserved;
9336 FieldTypes[2] = Context->UnsignedShortTy;
9337 FieldNames[2] = "reserved";
9338
9339 // void* overflow_arg_area;
9340 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
9341 FieldNames[3] = "overflow_arg_area";
9342
9343 // void* reg_save_area;
9344 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
9345 FieldNames[4] = "reg_save_area";
9346
9347 // Create fields
9348 for (unsigned i = 0; i < NumFields; ++i) {
9349 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
9352 &Context->Idents.get(FieldNames[i]),
9353 FieldTypes[i], /*TInfo=*/nullptr,
9354 /*BitWidth=*/nullptr,
9355 /*Mutable=*/false,
9356 ICIS_NoInit);
9357 Field->setAccess(AS_public);
9358 VaListTagDecl->addDecl(Field);
9359 }
9360 VaListTagDecl->completeDefinition();
9361 Context->VaListTagDecl = VaListTagDecl;
9362 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
9363
9364 // } __va_list_tag;
9365 TypedefDecl *VaListTagTypedefDecl =
9366 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
9367
9368 QualType VaListTagTypedefType =
9369 Context->getTypedefType(VaListTagTypedefDecl);
9370
9371 // typedef __va_list_tag __builtin_va_list[1];
9372 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
9373 QualType VaListTagArrayType = Context->getConstantArrayType(
9374 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
9375 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
9376}
9377
9378static TypedefDecl *
9380 // struct __va_list_tag {
9381 RecordDecl *VaListTagDecl;
9382 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
9383 VaListTagDecl->startDefinition();
9384
9385 const size_t NumFields = 4;
9386 QualType FieldTypes[NumFields];
9387 const char *FieldNames[NumFields];
9388
9389 // unsigned gp_offset;
9390 FieldTypes[0] = Context->UnsignedIntTy;
9391 FieldNames[0] = "gp_offset";
9392
9393 // unsigned fp_offset;
9394 FieldTypes[1] = Context->UnsignedIntTy;
9395 FieldNames[1] = "fp_offset";
9396
9397 // void* overflow_arg_area;
9398 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
9399 FieldNames[2] = "overflow_arg_area";
9400
9401 // void* reg_save_area;
9402 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
9403 FieldNames[3] = "reg_save_area";
9404
9405 // Create fields
9406 for (unsigned i = 0; i < NumFields; ++i) {
9407 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
9408 VaListTagDecl,
9411 &Context->Idents.get(FieldNames[i]),
9412 FieldTypes[i], /*TInfo=*/nullptr,
9413 /*BitWidth=*/nullptr,
9414 /*Mutable=*/false,
9415 ICIS_NoInit);
9416 Field->setAccess(AS_public);
9417 VaListTagDecl->addDecl(Field);
9418 }
9419 VaListTagDecl->completeDefinition();
9420 Context->VaListTagDecl = VaListTagDecl;
9421 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
9422
9423 // };
9424
9425 // typedef struct __va_list_tag __builtin_va_list[1];
9426 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
9427 QualType VaListTagArrayType = Context->getConstantArrayType(
9428 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
9429 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
9430}
9431
9433 // typedef int __builtin_va_list[4];
9434 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
9435 QualType IntArrayType = Context->getConstantArrayType(
9436 Context->IntTy, Size, nullptr, ArraySizeModifier::Normal, 0);
9437 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
9438}
9439
9440static TypedefDecl *
9442 // struct __va_list
9443 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
9444 if (Context->getLangOpts().CPlusPlus) {
9445 // namespace std { struct __va_list {
9446 NamespaceDecl *NS;
9447 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
9448 Context->getTranslationUnitDecl(),
9449 /*Inline=*/false, SourceLocation(),
9450 SourceLocation(), &Context->Idents.get("std"),
9451 /*PrevDecl=*/nullptr, /*Nested=*/false);
9452 NS->setImplicit();
9453 VaListDecl->setDeclContext(NS);
9454 }
9455
9456 VaListDecl->startDefinition();
9457
9458 // void * __ap;
9459 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
9460 VaListDecl,
9463 &Context->Idents.get("__ap"),
9464 Context->getPointerType(Context->VoidTy),
9465 /*TInfo=*/nullptr,
9466 /*BitWidth=*/nullptr,
9467 /*Mutable=*/false,
9468 ICIS_NoInit);
9469 Field->setAccess(AS_public);
9470 VaListDecl->addDecl(Field);
9471
9472 // };
9473 VaListDecl->completeDefinition();
9474 Context->VaListTagDecl = VaListDecl;
9475
9476 // typedef struct __va_list __builtin_va_list;
9477 QualType T = Context->getRecordType(VaListDecl);
9478 return Context->buildImplicitTypedef(T, "__builtin_va_list");
9479}
9480
9481static TypedefDecl *
9483 // struct __va_list_tag {
9484 RecordDecl *VaListTagDecl;
9485 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
9486 VaListTagDecl->startDefinition();
9487
9488 const size_t NumFields = 4;
9489 QualType FieldTypes[NumFields];
9490 const char *FieldNames[NumFields];
9491
9492 // long __gpr;
9493 FieldTypes[0] = Context->LongTy;
9494 FieldNames[0] = "__gpr";
9495
9496 // long __fpr;
9497 FieldTypes[1] = Context->LongTy;
9498 FieldNames[1] = "__fpr";
9499
9500 // void *__overflow_arg_area;
9501 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
9502 FieldNames[2] = "__overflow_arg_area";
9503
9504 // void *__reg_save_area;
9505 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
9506 FieldNames[3] = "__reg_save_area";
9507
9508 // Create fields
9509 for (unsigned i = 0; i < NumFields; ++i) {
9510 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
9511 VaListTagDecl,
9514 &Context->Idents.get(FieldNames[i]),
9515 FieldTypes[i], /*TInfo=*/nullptr,
9516 /*BitWidth=*/nullptr,
9517 /*Mutable=*/false,
9518 ICIS_NoInit);
9519 Field->setAccess(AS_public);
9520 VaListTagDecl->addDecl(Field);
9521 }
9522 VaListTagDecl->completeDefinition();
9523 Context->VaListTagDecl = VaListTagDecl;
9524 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
9525
9526 // };
9527
9528 // typedef __va_list_tag __builtin_va_list[1];
9529 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
9530 QualType VaListTagArrayType = Context->getConstantArrayType(
9531 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
9532
9533 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
9534}
9535
9537 // typedef struct __va_list_tag {
9538 RecordDecl *VaListTagDecl;
9539 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
9540 VaListTagDecl->startDefinition();
9541
9542 const size_t NumFields = 3;
9543 QualType FieldTypes[NumFields];
9544 const char *FieldNames[NumFields];
9545
9546 // void *CurrentSavedRegisterArea;
9547 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
9548 FieldNames[0] = "__current_saved_reg_area_pointer";
9549
9550 // void *SavedRegAreaEnd;
9551 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
9552 FieldNames[1] = "__saved_reg_area_end_pointer";
9553
9554 // void *OverflowArea;
9555 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
9556 FieldNames[2] = "__overflow_area_pointer";
9557
9558 // Create fields
9559 for (unsigned i = 0; i < NumFields; ++i) {
9561 const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(),
9562 SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i],
9563 /*TInfo=*/nullptr,
9564 /*BitWidth=*/nullptr,
9565 /*Mutable=*/false, ICIS_NoInit);
9566 Field->setAccess(AS_public);
9567 VaListTagDecl->addDecl(Field);
9568 }
9569 VaListTagDecl->completeDefinition();
9570 Context->VaListTagDecl = VaListTagDecl;
9571 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
9572
9573 // } __va_list_tag;
9574 TypedefDecl *VaListTagTypedefDecl =
9575 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
9576
9577 QualType VaListTagTypedefType = Context->getTypedefType(VaListTagTypedefDecl);
9578
9579 // typedef __va_list_tag __builtin_va_list[1];
9580 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
9581 QualType VaListTagArrayType = Context->getConstantArrayType(
9582 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
9583
9584 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
9585}
9586
9589 switch (Kind) {
9591 return CreateCharPtrBuiltinVaListDecl(Context);
9593 return CreateVoidPtrBuiltinVaListDecl(Context);
9595 return CreateAArch64ABIBuiltinVaListDecl(Context);
9597 return CreatePowerABIBuiltinVaListDecl(Context);
9599 return CreateX86_64ABIBuiltinVaListDecl(Context);
9601 return CreatePNaClABIBuiltinVaListDecl(Context);
9603 return CreateAAPCSABIBuiltinVaListDecl(Context);
9605 return CreateSystemZBuiltinVaListDecl(Context);
9607 return CreateHexagonBuiltinVaListDecl(Context);
9608 }
9609
9610 llvm_unreachable("Unhandled __builtin_va_list type kind");
9611}
9612
9614 if (!BuiltinVaListDecl) {
9615 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
9616 assert(BuiltinVaListDecl->isImplicit());
9617 }
9618
9619 return BuiltinVaListDecl;
9620}
9621
9623 // Force the creation of VaListTagDecl by building the __builtin_va_list
9624 // declaration.
9625 if (!VaListTagDecl)
9626 (void)getBuiltinVaListDecl();
9627
9628 return VaListTagDecl;
9629}
9630
9632 if (!BuiltinMSVaListDecl)
9633 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
9634
9635 return BuiltinMSVaListDecl;
9636}
9637
9639 // Allow redecl custom type checking builtin for HLSL.
9640 if (LangOpts.HLSL && FD->getBuiltinID() != Builtin::NotBuiltin &&
9642 return true;
9644}
9645
9647 assert(ObjCConstantStringType.isNull() &&
9648 "'NSConstantString' type already set!");
9649
9650 ObjCConstantStringType = getObjCInterfaceType(Decl);
9651}
9652
9653/// Retrieve the template name that corresponds to a non-empty
9654/// lookup.
9657 UnresolvedSetIterator End) const {
9658 unsigned size = End - Begin;
9659 assert(size > 1 && "set is not overloaded!");
9660
9661 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
9662 size * sizeof(FunctionTemplateDecl*));
9663 auto *OT = new (memory) OverloadedTemplateStorage(size);
9664
9665 NamedDecl **Storage = OT->getStorage();
9666 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
9667 NamedDecl *D = *I;
9668 assert(isa<FunctionTemplateDecl>(D) ||
9669 isa<UnresolvedUsingValueDecl>(D) ||
9670 (isa<UsingShadowDecl>(D) &&
9671 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
9672 *Storage++ = D;
9673 }
9674
9675 return TemplateName(OT);
9676}
9677
9678/// Retrieve a template name representing an unqualified-id that has been
9679/// assumed to name a template for ADL purposes.
9681 auto *OT = new (*this) AssumedTemplateStorage(Name);
9682 return TemplateName(OT);
9683}
9684
9685/// Retrieve the template name that represents a qualified
9686/// template name such as \c std::vector.
9688 bool TemplateKeyword,
9689 TemplateName Template) const {
9690 assert(Template.getKind() == TemplateName::Template ||
9691 Template.getKind() == TemplateName::UsingTemplate);
9692
9693 // FIXME: Canonicalization?
9694 llvm::FoldingSetNodeID ID;
9695 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
9696
9697 void *InsertPos = nullptr;
9699 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
9700 if (!QTN) {
9701 QTN = new (*this, alignof(QualifiedTemplateName))
9702 QualifiedTemplateName(NNS, TemplateKeyword, Template);
9703 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
9704 }
9705
9706 return TemplateName(QTN);
9707}
9708
9709/// Retrieve the template name that represents a dependent
9710/// template name such as \c MetaFun::template apply.
9713 const IdentifierInfo *Name) const {
9714 assert((!NNS || NNS->isDependent()) &&
9715 "Nested name specifier must be dependent");
9716
9717 llvm::FoldingSetNodeID ID;
9718 DependentTemplateName::Profile(ID, NNS, Name);
9719
9720 void *InsertPos = nullptr;
9722 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
9723
9724 if (QTN)
9725 return TemplateName(QTN);
9726
9728 if (CanonNNS == NNS) {
9729 QTN = new (*this, alignof(DependentTemplateName))
9730 DependentTemplateName(NNS, Name);
9731 } else {
9732 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
9733 QTN = new (*this, alignof(DependentTemplateName))
9734 DependentTemplateName(NNS, Name, Canon);
9735 DependentTemplateName *CheckQTN =
9736 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
9737 assert(!CheckQTN && "Dependent type name canonicalization broken");
9738 (void)CheckQTN;
9739 }
9740
9741 DependentTemplateNames.InsertNode(QTN, InsertPos);
9742 return TemplateName(QTN);
9743}
9744
9745/// Retrieve the template name that represents a dependent
9746/// template name such as \c MetaFun::template operator+.
9749 OverloadedOperatorKind Operator) const {
9750 assert((!NNS || NNS->isDependent()) &&
9751 "Nested name specifier must be dependent");
9752
9753 llvm::FoldingSetNodeID ID;
9754 DependentTemplateName::Profile(ID, NNS, Operator);
9755
9756 void *InsertPos = nullptr;
9758 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
9759
9760 if (QTN)
9761 return TemplateName(QTN);
9762
9764 if (CanonNNS == NNS) {
9765 QTN = new (*this, alignof(DependentTemplateName))
9766 DependentTemplateName(NNS, Operator);
9767 } else {
9768 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
9769 QTN = new (*this, alignof(DependentTemplateName))
9770 DependentTemplateName(NNS, Operator, Canon);
9771
9772 DependentTemplateName *CheckQTN
9773 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
9774 assert(!CheckQTN && "Dependent template name canonicalization broken");
9775 (void)CheckQTN;
9776 }
9777
9778 DependentTemplateNames.InsertNode(QTN, InsertPos);
9779 return TemplateName(QTN);
9780}
9781
9783 TemplateName Replacement, Decl *AssociatedDecl, unsigned Index,
9784 std::optional<unsigned> PackIndex) const {
9785 llvm::FoldingSetNodeID ID;
9786 SubstTemplateTemplateParmStorage::Profile(ID, Replacement, AssociatedDecl,
9787 Index, PackIndex);
9788
9789 void *insertPos = nullptr;
9791 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
9792
9793 if (!subst) {
9794 subst = new (*this) SubstTemplateTemplateParmStorage(
9795 Replacement, AssociatedDecl, Index, PackIndex);
9796 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
9797 }
9798
9799 return TemplateName(subst);
9800}
9801
9804 Decl *AssociatedDecl,
9805 unsigned Index, bool Final) const {
9806 auto &Self = const_cast<ASTContext &>(*this);
9807 llvm::FoldingSetNodeID ID;
9809 AssociatedDecl, Index, Final);
9810
9811 void *InsertPos = nullptr;
9813 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
9814
9815 if (!Subst) {
9816 Subst = new (*this) SubstTemplateTemplateParmPackStorage(
9817 ArgPack.pack_elements(), AssociatedDecl, Index, Final);
9818 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
9819 }
9820
9821 return TemplateName(Subst);
9822}
9823
9824/// getFromTargetType - Given one of the integer types provided by
9825/// TargetInfo, produce the corresponding type. The unsigned @p Type
9826/// is actually a value of type @c TargetInfo::IntType.
9827CanQualType ASTContext::getFromTargetType(unsigned Type) const {
9828 switch (Type) {
9829 case TargetInfo::NoInt: return {};
9832 case TargetInfo::SignedShort: return ShortTy;
9834 case TargetInfo::SignedInt: return IntTy;
9836 case TargetInfo::SignedLong: return LongTy;
9840 }
9841
9842 llvm_unreachable("Unhandled TargetInfo::IntType value");
9843}
9844
9845//===----------------------------------------------------------------------===//
9846// Type Predicates.
9847//===----------------------------------------------------------------------===//
9848
9849/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
9850/// garbage collection attribute.
9851///
9853 if (getLangOpts().getGC() == LangOptions::NonGC)
9854 return Qualifiers::GCNone;
9855
9856 assert(getLangOpts().ObjC);
9857 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
9858
9859 // Default behaviour under objective-C's gc is for ObjC pointers
9860 // (or pointers to them) be treated as though they were declared
9861 // as __strong.
9862 if (GCAttrs == Qualifiers::GCNone) {
9864 return Qualifiers::Strong;
9865 else if (Ty->isPointerType())
9867 } else {
9868 // It's not valid to set GC attributes on anything that isn't a
9869 // pointer.
9870#ifndef NDEBUG
9872 while (const auto *AT = dyn_cast<ArrayType>(CT))
9873 CT = AT->getElementType();
9874 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
9875#endif
9876 }
9877 return GCAttrs;
9878}
9879
9880//===----------------------------------------------------------------------===//
9881// Type Compatibility Testing
9882//===----------------------------------------------------------------------===//
9883
9884/// areCompatVectorTypes - Return true if the two specified vector types are
9885/// compatible.
9886static bool areCompatVectorTypes(const VectorType *LHS,
9887 const VectorType *RHS) {
9888 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
9889 return LHS->getElementType() == RHS->getElementType() &&
9890 LHS->getNumElements() == RHS->getNumElements();
9891}
9892
9893/// areCompatMatrixTypes - Return true if the two specified matrix types are
9894/// compatible.
9896 const ConstantMatrixType *RHS) {
9897 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
9898 return LHS->getElementType() == RHS->getElementType() &&
9899 LHS->getNumRows() == RHS->getNumRows() &&
9900 LHS->getNumColumns() == RHS->getNumColumns();
9901}
9902
9904 QualType SecondVec) {
9905 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
9906 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
9907
9908 if (hasSameUnqualifiedType(FirstVec, SecondVec))
9909 return true;
9910
9911 // Treat Neon vector types and most AltiVec vector types as if they are the
9912 // equivalent GCC vector types.
9913 const auto *First = FirstVec->castAs<VectorType>();
9914 const auto *Second = SecondVec->castAs<VectorType>();
9915 if (First->getNumElements() == Second->getNumElements() &&
9916 hasSameType(First->getElementType(), Second->getElementType()) &&
9917 First->getVectorKind() != VectorKind::AltiVecPixel &&
9918 First->getVectorKind() != VectorKind::AltiVecBool &&
9921 First->getVectorKind() != VectorKind::SveFixedLengthData &&
9922 First->getVectorKind() != VectorKind::SveFixedLengthPredicate &&
9925 First->getVectorKind() != VectorKind::RVVFixedLengthData &&
9927 First->getVectorKind() != VectorKind::RVVFixedLengthMask &&
9929 First->getVectorKind() != VectorKind::RVVFixedLengthMask_1 &&
9931 First->getVectorKind() != VectorKind::RVVFixedLengthMask_2 &&
9933 First->getVectorKind() != VectorKind::RVVFixedLengthMask_4 &&
9935 return true;
9936
9937 return false;
9938}
9939
9940/// getSVETypeSize - Return SVE vector or predicate register size.
9941static uint64_t getSVETypeSize(ASTContext &Context, const BuiltinType *Ty) {
9942 assert(Ty->isSveVLSBuiltinType() && "Invalid SVE Type");
9943 if (Ty->getKind() == BuiltinType::SveBool ||
9944 Ty->getKind() == BuiltinType::SveCount)
9945 return (Context.getLangOpts().VScaleMin * 128) / Context.getCharWidth();
9946 return Context.getLangOpts().VScaleMin * 128;
9947}
9948
9950 QualType SecondType) {
9951 auto IsValidCast = [this](QualType FirstType, QualType SecondType) {
9952 if (const auto *BT = FirstType->getAs<BuiltinType>()) {
9953 if (const auto *VT = SecondType->getAs<VectorType>()) {
9954 // Predicates have the same representation as uint8 so we also have to
9955 // check the kind to make these types incompatible.
9956 if (VT->getVectorKind() == VectorKind::SveFixedLengthPredicate)
9957 return BT->getKind() == BuiltinType::SveBool;
9958 else if (VT->getVectorKind() == VectorKind::SveFixedLengthData)
9959 return VT->getElementType().getCanonicalType() ==
9960 FirstType->getSveEltType(*this);
9961 else if (VT->getVectorKind() == VectorKind::Generic)
9962 return getTypeSize(SecondType) == getSVETypeSize(*this, BT) &&
9963 hasSameType(VT->getElementType(),
9964 getBuiltinVectorTypeInfo(BT).ElementType);
9965 }
9966 }
9967 return false;
9968 };
9969
9970 return IsValidCast(FirstType, SecondType) ||
9971 IsValidCast(SecondType, FirstType);
9972}
9973
9975 QualType SecondType) {
9976 auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) {
9977 const auto *BT = FirstType->getAs<BuiltinType>();
9978 if (!BT)
9979 return false;
9980
9981 const auto *VecTy = SecondType->getAs<VectorType>();
9982 if (VecTy && (VecTy->getVectorKind() == VectorKind::SveFixedLengthData ||
9983 VecTy->getVectorKind() == VectorKind::Generic)) {
9985 getLangOpts().getLaxVectorConversions();
9986
9987 // Can not convert between sve predicates and sve vectors because of
9988 // different size.
9989 if (BT->getKind() == BuiltinType::SveBool &&
9990 VecTy->getVectorKind() == VectorKind::SveFixedLengthData)
9991 return false;
9992
9993 // If __ARM_FEATURE_SVE_BITS != N do not allow GNU vector lax conversion.
9994 // "Whenever __ARM_FEATURE_SVE_BITS==N, GNUT implicitly
9995 // converts to VLAT and VLAT implicitly converts to GNUT."
9996 // ACLE Spec Version 00bet6, 3.7.3.2. Behavior common to vectors and
9997 // predicates.
9998 if (VecTy->getVectorKind() == VectorKind::Generic &&
9999 getTypeSize(SecondType) != getSVETypeSize(*this, BT))
10000 return false;
10001
10002 // If -flax-vector-conversions=all is specified, the types are
10003 // certainly compatible.
10005 return true;
10006
10007 // If -flax-vector-conversions=integer is specified, the types are
10008 // compatible if the elements are integer types.
10010 return VecTy->getElementType().getCanonicalType()->isIntegerType() &&
10011 FirstType->getSveEltType(*this)->isIntegerType();
10012 }
10013
10014 return false;
10015 };
10016
10017 return IsLaxCompatible(FirstType, SecondType) ||
10018 IsLaxCompatible(SecondType, FirstType);
10019}
10020
10021/// getRVVTypeSize - Return RVV vector register size.
10022static uint64_t getRVVTypeSize(ASTContext &Context, const BuiltinType *Ty) {
10023 assert(Ty->isRVVVLSBuiltinType() && "Invalid RVV Type");
10024 auto VScale = Context.getTargetInfo().getVScaleRange(Context.getLangOpts());
10025 if (!VScale)
10026 return 0;
10027
10029
10030 uint64_t EltSize = Context.getTypeSize(Info.ElementType);
10031 if (Info.ElementType == Context.BoolTy)
10032 EltSize = 1;
10033
10034 uint64_t MinElts = Info.EC.getKnownMinValue();
10035 return VScale->first * MinElts * EltSize;
10036}
10037
10039 QualType SecondType) {
10040 assert(
10041 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10042 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10043 "Expected RVV builtin type and vector type!");
10044
10045 auto IsValidCast = [this](QualType FirstType, QualType SecondType) {
10046 if (const auto *BT = FirstType->getAs<BuiltinType>()) {
10047 if (const auto *VT = SecondType->getAs<VectorType>()) {
10048 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask) {
10050 return FirstType->isRVVVLSBuiltinType() &&
10051 Info.ElementType == BoolTy &&
10052 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)));
10053 }
10054 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_1) {
10056 return FirstType->isRVVVLSBuiltinType() &&
10057 Info.ElementType == BoolTy &&
10058 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT) * 8));
10059 }
10060 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_2) {
10062 return FirstType->isRVVVLSBuiltinType() &&
10063 Info.ElementType == BoolTy &&
10064 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)) * 4);
10065 }
10066 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_4) {
10068 return FirstType->isRVVVLSBuiltinType() &&
10069 Info.ElementType == BoolTy &&
10070 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)) * 2);
10071 }
10072 if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
10073 VT->getVectorKind() == VectorKind::Generic)
10074 return FirstType->isRVVVLSBuiltinType() &&
10075 getTypeSize(SecondType) == getRVVTypeSize(*this, BT) &&
10076 hasSameType(VT->getElementType(),
10077 getBuiltinVectorTypeInfo(BT).ElementType);
10078 }
10079 }
10080 return false;
10081 };
10082
10083 return IsValidCast(FirstType, SecondType) ||
10084 IsValidCast(SecondType, FirstType);
10085}
10086
10088 QualType SecondType) {
10089 assert(
10090 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10091 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10092 "Expected RVV builtin type and vector type!");
10093
10094 auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) {
10095 const auto *BT = FirstType->getAs<BuiltinType>();
10096 if (!BT)
10097 return false;
10098
10099 if (!BT->isRVVVLSBuiltinType())
10100 return false;
10101
10102 const auto *VecTy = SecondType->getAs<VectorType>();
10103 if (VecTy && VecTy->getVectorKind() == VectorKind::Generic) {
10105 getLangOpts().getLaxVectorConversions();
10106
10107 // If __riscv_v_fixed_vlen != N do not allow vector lax conversion.
10108 if (getTypeSize(SecondType) != getRVVTypeSize(*this, BT))
10109 return false;
10110
10111 // If -flax-vector-conversions=all is specified, the types are
10112 // certainly compatible.
10114 return true;
10115
10116 // If -flax-vector-conversions=integer is specified, the types are
10117 // compatible if the elements are integer types.
10119 return VecTy->getElementType().getCanonicalType()->isIntegerType() &&
10120 FirstType->getRVVEltType(*this)->isIntegerType();
10121 }
10122
10123 return false;
10124 };
10125
10126 return IsLaxCompatible(FirstType, SecondType) ||
10127 IsLaxCompatible(SecondType, FirstType);
10128}
10129
10131 while (true) {
10132 // __strong id
10133 if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) {
10134 if (Attr->getAttrKind() == attr::ObjCOwnership)
10135 return true;
10136
10137 Ty = Attr->getModifiedType();
10138
10139 // X *__strong (...)
10140 } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) {
10141 Ty = Paren->getInnerType();
10142
10143 // We do not want to look through typedefs, typeof(expr),
10144 // typeof(type), or any other way that the type is somehow
10145 // abstracted.
10146 } else {
10147 return false;
10148 }
10149 }
10150}
10151
10152//===----------------------------------------------------------------------===//
10153// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
10154//===----------------------------------------------------------------------===//
10155
10156/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
10157/// inheritance hierarchy of 'rProto'.
10158bool
10160 ObjCProtocolDecl *rProto) const {
10161 if (declaresSameEntity(lProto, rProto))
10162 return true;
10163 for (auto *PI : rProto->protocols())
10164 if (ProtocolCompatibleWithProtocol(lProto, PI))
10165 return true;
10166 return false;
10167}
10168
10169/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
10170/// Class<pr1, ...>.
10172 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) {
10173 for (auto *lhsProto : lhs->quals()) {
10174 bool match = false;
10175 for (auto *rhsProto : rhs->quals()) {
10176 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
10177 match = true;
10178 break;
10179 }
10180 }
10181 if (!match)
10182 return false;
10183 }
10184 return true;
10185}
10186
10187/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
10188/// ObjCQualifiedIDType.
10190 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs,
10191 bool compare) {
10192 // Allow id<P..> and an 'id' in all cases.
10193 if (lhs->isObjCIdType() || rhs->isObjCIdType())
10194 return true;
10195
10196 // Don't allow id<P..> to convert to Class or Class<P..> in either direction.
10197 if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() ||
10199 return false;
10200
10201 if (lhs->isObjCQualifiedIdType()) {
10202 if (rhs->qual_empty()) {
10203 // If the RHS is a unqualified interface pointer "NSString*",
10204 // make sure we check the class hierarchy.
10205 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
10206 for (auto *I : lhs->quals()) {
10207 // when comparing an id<P> on lhs with a static type on rhs,
10208 // see if static class implements all of id's protocols, directly or
10209 // through its super class and categories.
10210 if (!rhsID->ClassImplementsProtocol(I, true))
10211 return false;
10212 }
10213 }
10214 // If there are no qualifiers and no interface, we have an 'id'.
10215 return true;
10216 }
10217 // Both the right and left sides have qualifiers.
10218 for (auto *lhsProto : lhs->quals()) {
10219 bool match = false;
10220
10221 // when comparing an id<P> on lhs with a static type on rhs,
10222 // see if static class implements all of id's protocols, directly or
10223 // through its super class and categories.
10224 for (auto *rhsProto : rhs->quals()) {
10225 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
10226 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
10227 match = true;
10228 break;
10229 }
10230 }
10231 // If the RHS is a qualified interface pointer "NSString<P>*",
10232 // make sure we check the class hierarchy.
10233 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
10234 for (auto *I : lhs->quals()) {
10235 // when comparing an id<P> on lhs with a static type on rhs,
10236 // see if static class implements all of id's protocols, directly or
10237 // through its super class and categories.
10238 if (rhsID->ClassImplementsProtocol(I, true)) {
10239 match = true;
10240 break;
10241 }
10242 }
10243 }
10244 if (!match)
10245 return false;
10246 }
10247
10248 return true;
10249 }
10250
10251 assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>");
10252
10253 if (lhs->getInterfaceType()) {
10254 // If both the right and left sides have qualifiers.
10255 for (auto *lhsProto : lhs->quals()) {
10256 bool match = false;
10257
10258 // when comparing an id<P> on rhs with a static type on lhs,
10259 // see if static class implements all of id's protocols, directly or
10260 // through its super class and categories.
10261 // First, lhs protocols in the qualifier list must be found, direct
10262 // or indirect in rhs's qualifier list or it is a mismatch.
10263 for (auto *rhsProto : rhs->quals()) {
10264 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
10265 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
10266 match = true;
10267 break;
10268 }
10269 }
10270 if (!match)
10271 return false;
10272 }
10273
10274 // Static class's protocols, or its super class or category protocols
10275 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
10276 if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) {
10277 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
10278 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
10279 // This is rather dubious but matches gcc's behavior. If lhs has
10280 // no type qualifier and its class has no static protocol(s)
10281 // assume that it is mismatch.
10282 if (LHSInheritedProtocols.empty() && lhs->qual_empty())
10283 return false;
10284 for (auto *lhsProto : LHSInheritedProtocols) {
10285 bool match = false;
10286 for (auto *rhsProto : rhs->quals()) {
10287 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
10288 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
10289 match = true;
10290 break;
10291 }
10292 }
10293 if (!match)
10294 return false;
10295 }
10296 }
10297 return true;
10298 }
10299 return false;
10300}
10301
10302/// canAssignObjCInterfaces - Return true if the two interface types are
10303/// compatible for assignment from RHS to LHS. This handles validation of any
10304/// protocol qualifiers on the LHS or RHS.
10306 const ObjCObjectPointerType *RHSOPT) {
10307 const ObjCObjectType* LHS = LHSOPT->getObjectType();
10308 const ObjCObjectType* RHS = RHSOPT->getObjectType();
10309
10310 // If either type represents the built-in 'id' type, return true.
10311 if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId())
10312 return true;
10313
10314 // Function object that propagates a successful result or handles
10315 // __kindof types.
10316 auto finish = [&](bool succeeded) -> bool {
10317 if (succeeded)
10318 return true;
10319
10320 if (!RHS->isKindOfType())
10321 return false;
10322
10323 // Strip off __kindof and protocol qualifiers, then check whether
10324 // we can assign the other way.
10326 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
10327 };
10328
10329 // Casts from or to id<P> are allowed when the other side has compatible
10330 // protocols.
10331 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
10332 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false));
10333 }
10334
10335 // Verify protocol compatibility for casts from Class<P1> to Class<P2>.
10336 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
10337 return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT));
10338 }
10339
10340 // Casts from Class to Class<Foo>, or vice-versa, are allowed.
10341 if (LHS->isObjCClass() && RHS->isObjCClass()) {
10342 return true;
10343 }
10344
10345 // If we have 2 user-defined types, fall into that path.
10346 if (LHS->getInterface() && RHS->getInterface()) {
10347 return finish(canAssignObjCInterfaces(LHS, RHS));
10348 }
10349
10350 return false;
10351}
10352
10353/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
10354/// for providing type-safety for objective-c pointers used to pass/return
10355/// arguments in block literals. When passed as arguments, passing 'A*' where
10356/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
10357/// not OK. For the return type, the opposite is not OK.
10359 const ObjCObjectPointerType *LHSOPT,
10360 const ObjCObjectPointerType *RHSOPT,
10361 bool BlockReturnType) {
10362
10363 // Function object that propagates a successful result or handles
10364 // __kindof types.
10365 auto finish = [&](bool succeeded) -> bool {
10366 if (succeeded)
10367 return true;
10368
10369 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
10370 if (!Expected->isKindOfType())
10371 return false;
10372
10373 // Strip off __kindof and protocol qualifiers, then check whether
10374 // we can assign the other way.
10376 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
10377 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
10378 BlockReturnType);
10379 };
10380
10381 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
10382 return true;
10383
10384 if (LHSOPT->isObjCBuiltinType()) {
10385 return finish(RHSOPT->isObjCBuiltinType() ||
10386 RHSOPT->isObjCQualifiedIdType());
10387 }
10388
10389 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) {
10390 if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking)
10391 // Use for block parameters previous type checking for compatibility.
10392 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false) ||
10393 // Or corrected type checking as in non-compat mode.
10394 (!BlockReturnType &&
10395 ObjCQualifiedIdTypesAreCompatible(RHSOPT, LHSOPT, false)));
10396 else
10398 (BlockReturnType ? LHSOPT : RHSOPT),
10399 (BlockReturnType ? RHSOPT : LHSOPT), false));
10400 }
10401
10402 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
10403 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
10404 if (LHS && RHS) { // We have 2 user-defined types.
10405 if (LHS != RHS) {
10406 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
10407 return finish(BlockReturnType);
10408 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
10409 return finish(!BlockReturnType);
10410 }
10411 else
10412 return true;
10413 }
10414 return false;
10415}
10416
10417/// Comparison routine for Objective-C protocols to be used with
10418/// llvm::array_pod_sort.
10420 ObjCProtocolDecl * const *rhs) {
10421 return (*lhs)->getName().compare((*rhs)->getName());
10422}
10423
10424/// getIntersectionOfProtocols - This routine finds the intersection of set
10425/// of protocols inherited from two distinct objective-c pointer objects with
10426/// the given common base.
10427/// It is used to build composite qualifier list of the composite type of
10428/// the conditional expression involving two objective-c pointer objects.
10429static
10431 const ObjCInterfaceDecl *CommonBase,
10432 const ObjCObjectPointerType *LHSOPT,
10433 const ObjCObjectPointerType *RHSOPT,
10434 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
10435
10436 const ObjCObjectType* LHS = LHSOPT->getObjectType();
10437 const ObjCObjectType* RHS = RHSOPT->getObjectType();
10438 assert(LHS->getInterface() && "LHS must have an interface base");
10439 assert(RHS->getInterface() && "RHS must have an interface base");
10440
10441 // Add all of the protocols for the LHS.
10443
10444 // Start with the protocol qualifiers.
10445 for (auto *proto : LHS->quals()) {
10446 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
10447 }
10448
10449 // Also add the protocols associated with the LHS interface.
10450 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
10451
10452 // Add all of the protocols for the RHS.
10454
10455 // Start with the protocol qualifiers.
10456 for (auto *proto : RHS->quals()) {
10457 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
10458 }
10459
10460 // Also add the protocols associated with the RHS interface.
10461 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
10462
10463 // Compute the intersection of the collected protocol sets.
10464 for (auto *proto : LHSProtocolSet) {
10465 if (RHSProtocolSet.count(proto))
10466 IntersectionSet.push_back(proto);
10467 }
10468
10469 // Compute the set of protocols that is implied by either the common type or
10470 // the protocols within the intersection.
10472 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
10473
10474 // Remove any implied protocols from the list of inherited protocols.
10475 if (!ImpliedProtocols.empty()) {
10476 llvm::erase_if(IntersectionSet, [&](ObjCProtocolDecl *proto) -> bool {
10477 return ImpliedProtocols.contains(proto);
10478 });
10479 }
10480
10481 // Sort the remaining protocols by name.
10482 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
10484}
10485
10486/// Determine whether the first type is a subtype of the second.
10488 QualType rhs) {
10489 // Common case: two object pointers.
10490 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
10491 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
10492 if (lhsOPT && rhsOPT)
10493 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
10494
10495 // Two block pointers.
10496 const auto *lhsBlock = lhs->getAs<BlockPointerType>();
10497 const auto *rhsBlock = rhs->getAs<BlockPointerType>();
10498 if (lhsBlock && rhsBlock)
10499 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
10500
10501 // If either is an unqualified 'id' and the other is a block, it's
10502 // acceptable.
10503 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
10504 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
10505 return true;
10506
10507 return false;
10508}
10509
10510// Check that the given Objective-C type argument lists are equivalent.
10512 const ObjCInterfaceDecl *iface,
10513 ArrayRef<QualType> lhsArgs,
10514 ArrayRef<QualType> rhsArgs,
10515 bool stripKindOf) {
10516 if (lhsArgs.size() != rhsArgs.size())
10517 return false;
10518
10519 ObjCTypeParamList *typeParams = iface->getTypeParamList();
10520 if (!typeParams)
10521 return false;
10522
10523 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
10524 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
10525 continue;
10526
10527 switch (typeParams->begin()[i]->getVariance()) {
10529 if (!stripKindOf ||
10530 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
10531 rhsArgs[i].stripObjCKindOfType(ctx))) {
10532 return false;
10533 }
10534 break;
10535
10537 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
10538 return false;
10539 break;
10540
10542 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
10543 return false;
10544 break;
10545 }
10546 }
10547
10548 return true;
10549}
10550
10552 const ObjCObjectPointerType *Lptr,
10553 const ObjCObjectPointerType *Rptr) {
10554 const ObjCObjectType *LHS = Lptr->getObjectType();
10555 const ObjCObjectType *RHS = Rptr->getObjectType();
10556 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
10557 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
10558
10559 if (!LDecl || !RDecl)
10560 return {};
10561
10562 // When either LHS or RHS is a kindof type, we should return a kindof type.
10563 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
10564 // kindof(A).
10565 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
10566
10567 // Follow the left-hand side up the class hierarchy until we either hit a
10568 // root or find the RHS. Record the ancestors in case we don't find it.
10569 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
10570 LHSAncestors;
10571 while (true) {
10572 // Record this ancestor. We'll need this if the common type isn't in the
10573 // path from the LHS to the root.
10574 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
10575
10576 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
10577 // Get the type arguments.
10578 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
10579 bool anyChanges = false;
10580 if (LHS->isSpecialized() && RHS->isSpecialized()) {
10581 // Both have type arguments, compare them.
10582 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
10583 LHS->getTypeArgs(), RHS->getTypeArgs(),
10584 /*stripKindOf=*/true))
10585 return {};
10586 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
10587 // If only one has type arguments, the result will not have type
10588 // arguments.
10589 LHSTypeArgs = {};
10590 anyChanges = true;
10591 }
10592
10593 // Compute the intersection of protocols.
10595 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
10596 Protocols);
10597 if (!Protocols.empty())
10598 anyChanges = true;
10599
10600 // If anything in the LHS will have changed, build a new result type.
10601 // If we need to return a kindof type but LHS is not a kindof type, we
10602 // build a new result type.
10603 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
10605 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
10606 anyKindOf || LHS->isKindOfType());
10608 }
10609
10610 return getObjCObjectPointerType(QualType(LHS, 0));
10611 }
10612
10613 // Find the superclass.
10614 QualType LHSSuperType = LHS->getSuperClassType();
10615 if (LHSSuperType.isNull())
10616 break;
10617
10618 LHS = LHSSuperType->castAs<ObjCObjectType>();
10619 }
10620
10621 // We didn't find anything by following the LHS to its root; now check
10622 // the RHS against the cached set of ancestors.
10623 while (true) {
10624 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
10625 if (KnownLHS != LHSAncestors.end()) {
10626 LHS = KnownLHS->second;
10627
10628 // Get the type arguments.
10629 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
10630 bool anyChanges = false;
10631 if (LHS->isSpecialized() && RHS->isSpecialized()) {
10632 // Both have type arguments, compare them.
10633 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
10634 LHS->getTypeArgs(), RHS->getTypeArgs(),
10635 /*stripKindOf=*/true))
10636 return {};
10637 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
10638 // If only one has type arguments, the result will not have type
10639 // arguments.
10640 RHSTypeArgs = {};
10641 anyChanges = true;
10642 }
10643
10644 // Compute the intersection of protocols.
10646 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
10647 Protocols);
10648 if (!Protocols.empty())
10649 anyChanges = true;
10650
10651 // If we need to return a kindof type but RHS is not a kindof type, we
10652 // build a new result type.
10653 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
10655 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
10656 anyKindOf || RHS->isKindOfType());
10658 }
10659
10660 return getObjCObjectPointerType(QualType(RHS, 0));
10661 }
10662
10663 // Find the superclass of the RHS.
10664 QualType RHSSuperType = RHS->getSuperClassType();
10665 if (RHSSuperType.isNull())
10666 break;
10667
10668 RHS = RHSSuperType->castAs<ObjCObjectType>();
10669 }
10670
10671 return {};
10672}
10673
10675 const ObjCObjectType *RHS) {
10676 assert(LHS->getInterface() && "LHS is not an interface type");
10677 assert(RHS->getInterface() && "RHS is not an interface type");
10678
10679 // Verify that the base decls are compatible: the RHS must be a subclass of
10680 // the LHS.
10681 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
10682 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
10683 if (!IsSuperClass)
10684 return false;
10685
10686 // If the LHS has protocol qualifiers, determine whether all of them are
10687 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
10688 // LHS).
10689 if (LHS->getNumProtocols() > 0) {
10690 // OK if conversion of LHS to SuperClass results in narrowing of types
10691 // ; i.e., SuperClass may implement at least one of the protocols
10692 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
10693 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
10694 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
10695 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
10696 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
10697 // qualifiers.
10698 for (auto *RHSPI : RHS->quals())
10699 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
10700 // If there is no protocols associated with RHS, it is not a match.
10701 if (SuperClassInheritedProtocols.empty())
10702 return false;
10703
10704 for (const auto *LHSProto : LHS->quals()) {
10705 bool SuperImplementsProtocol = false;
10706 for (auto *SuperClassProto : SuperClassInheritedProtocols)
10707 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
10708 SuperImplementsProtocol = true;
10709 break;
10710 }
10711 if (!SuperImplementsProtocol)
10712 return false;
10713 }
10714 }
10715
10716 // If the LHS is specialized, we may need to check type arguments.
10717 if (LHS->isSpecialized()) {
10718 // Follow the superclass chain until we've matched the LHS class in the
10719 // hierarchy. This substitutes type arguments through.
10720 const ObjCObjectType *RHSSuper = RHS;
10721 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
10722 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
10723
10724 // If the RHS is specializd, compare type arguments.
10725 if (RHSSuper->isSpecialized() &&
10726 !sameObjCTypeArgs(*this, LHS->getInterface(),
10727 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
10728 /*stripKindOf=*/true)) {
10729 return false;
10730 }
10731 }
10732
10733 return true;
10734}
10735
10737 // get the "pointed to" types
10738 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
10739 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
10740
10741 if (!LHSOPT || !RHSOPT)
10742 return false;
10743
10744 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
10745 canAssignObjCInterfaces(RHSOPT, LHSOPT);
10746}
10747
10750 getObjCObjectPointerType(To)->castAs<ObjCObjectPointerType>(),
10751 getObjCObjectPointerType(From)->castAs<ObjCObjectPointerType>());
10752}
10753
10754/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
10755/// both shall have the identically qualified version of a compatible type.
10756/// C99 6.2.7p1: Two types have compatible types if their types are the
10757/// same. See 6.7.[2,3,5] for additional rules.
10759 bool CompareUnqualified) {
10760 if (getLangOpts().CPlusPlus)
10761 return hasSameType(LHS, RHS);
10762
10763 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
10764}
10765
10767 return typesAreCompatible(LHS, RHS);
10768}
10769
10771 return !mergeTypes(LHS, RHS, true).isNull();
10772}
10773
10774/// mergeTransparentUnionType - if T is a transparent union type and a member
10775/// of T is compatible with SubType, return the merged type, else return
10776/// QualType()
10778 bool OfBlockPointer,
10779 bool Unqualified) {
10780 if (const RecordType *UT = T->getAsUnionType()) {
10781 RecordDecl *UD = UT->getDecl();
10782 if (UD->hasAttr<TransparentUnionAttr>()) {
10783 for (const auto *I : UD->fields()) {
10784 QualType ET = I->getType().getUnqualifiedType();
10785 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
10786 if (!MT.isNull())
10787 return MT;
10788 }
10789 }
10790 }
10791
10792 return {};
10793}
10794
10795/// mergeFunctionParameterTypes - merge two types which appear as function
10796/// parameter types
10798 bool OfBlockPointer,
10799 bool Unqualified) {
10800 // GNU extension: two types are compatible if they appear as a function
10801 // argument, one of the types is a transparent union type and the other
10802 // type is compatible with a union member
10803 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
10804 Unqualified);
10805 if (!lmerge.isNull())
10806 return lmerge;
10807
10808 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
10809 Unqualified);
10810 if (!rmerge.isNull())
10811 return rmerge;
10812
10813 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
10814}
10815
10817 bool OfBlockPointer, bool Unqualified,
10818 bool AllowCXX,
10819 bool IsConditionalOperator) {
10820 const auto *lbase = lhs->castAs<FunctionType>();
10821 const auto *rbase = rhs->castAs<FunctionType>();
10822 const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
10823 const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
10824 bool allLTypes = true;
10825 bool allRTypes = true;
10826
10827 // Check return type
10828 QualType retType;
10829 if (OfBlockPointer) {
10830 QualType RHS = rbase->getReturnType();
10831 QualType LHS = lbase->getReturnType();
10832 bool UnqualifiedResult = Unqualified;
10833 if (!UnqualifiedResult)
10834 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
10835 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
10836 }
10837 else
10838 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
10839 Unqualified);
10840 if (retType.isNull())
10841 return {};
10842
10843 if (Unqualified)
10844 retType = retType.getUnqualifiedType();
10845
10846 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
10847 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
10848 if (Unqualified) {
10849 LRetType = LRetType.getUnqualifiedType();
10850 RRetType = RRetType.getUnqualifiedType();
10851 }
10852
10853 if (getCanonicalType(retType) != LRetType)
10854 allLTypes = false;
10855 if (getCanonicalType(retType) != RRetType)
10856 allRTypes = false;
10857
10858 // FIXME: double check this
10859 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
10860 // rbase->getRegParmAttr() != 0 &&
10861 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
10862 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
10863 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
10864
10865 // Compatible functions must have compatible calling conventions
10866 if (lbaseInfo.getCC() != rbaseInfo.getCC())
10867 return {};
10868
10869 // Regparm is part of the calling convention.
10870 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
10871 return {};
10872 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
10873 return {};
10874
10875 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
10876 return {};
10877 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
10878 return {};
10879 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
10880 return {};
10881
10882 // When merging declarations, it's common for supplemental information like
10883 // attributes to only be present in one of the declarations, and we generally
10884 // want type merging to preserve the union of information. So a merged
10885 // function type should be noreturn if it was noreturn in *either* operand
10886 // type.
10887 //
10888 // But for the conditional operator, this is backwards. The result of the
10889 // operator could be either operand, and its type should conservatively
10890 // reflect that. So a function type in a composite type is noreturn only
10891 // if it's noreturn in *both* operand types.
10892 //
10893 // Arguably, noreturn is a kind of subtype, and the conditional operator
10894 // ought to produce the most specific common supertype of its operand types.
10895 // That would differ from this rule in contravariant positions. However,
10896 // neither C nor C++ generally uses this kind of subtype reasoning. Also,
10897 // as a practical matter, it would only affect C code that does abstraction of
10898 // higher-order functions (taking noreturn callbacks!), which is uncommon to
10899 // say the least. So we use the simpler rule.
10900 bool NoReturn = IsConditionalOperator
10901 ? lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn()
10902 : lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
10903 if (lbaseInfo.getNoReturn() != NoReturn)
10904 allLTypes = false;
10905 if (rbaseInfo.getNoReturn() != NoReturn)
10906 allRTypes = false;
10907
10908 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
10909
10910 std::optional<FunctionEffectSet> MergedFX;
10911
10912 if (lproto && rproto) { // two C99 style function prototypes
10913 assert((AllowCXX ||
10914 (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) &&
10915 "C++ shouldn't be here");
10916 // Compatible functions must have the same number of parameters
10917 if (lproto->getNumParams() != rproto->getNumParams())
10918 return {};
10919
10920 // Variadic and non-variadic functions aren't compatible
10921 if (lproto->isVariadic() != rproto->isVariadic())
10922 return {};
10923
10924 if (lproto->getMethodQuals() != rproto->getMethodQuals())
10925 return {};
10926
10927 // Function effects are handled similarly to noreturn, see above.
10928 FunctionEffectsRef LHSFX = lproto->getFunctionEffects();
10929 FunctionEffectsRef RHSFX = rproto->getFunctionEffects();
10930 if (LHSFX != RHSFX) {
10931 if (IsConditionalOperator)
10932 MergedFX = FunctionEffectSet::getIntersection(LHSFX, RHSFX);
10933 else {
10935 MergedFX = FunctionEffectSet::getUnion(LHSFX, RHSFX, Errs);
10936 // Here we're discarding a possible error due to conflicts in the effect
10937 // sets. But we're not in a context where we can report it. The
10938 // operation does however guarantee maintenance of invariants.
10939 }
10940 if (*MergedFX != LHSFX)
10941 allLTypes = false;
10942 if (*MergedFX != RHSFX)
10943 allRTypes = false;
10944 }
10945
10947 bool canUseLeft, canUseRight;
10948 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
10949 newParamInfos))
10950 return {};
10951
10952 if (!canUseLeft)
10953 allLTypes = false;
10954 if (!canUseRight)
10955 allRTypes = false;
10956
10957 // Check parameter type compatibility
10959 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
10960 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
10961 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
10963 lParamType, rParamType, OfBlockPointer, Unqualified);
10964 if (paramType.isNull())
10965 return {};
10966
10967 if (Unqualified)
10968 paramType = paramType.getUnqualifiedType();
10969
10970 types.push_back(paramType);
10971 if (Unqualified) {
10972 lParamType = lParamType.getUnqualifiedType();
10973 rParamType = rParamType.getUnqualifiedType();
10974 }
10975
10976 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
10977 allLTypes = false;
10978 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
10979 allRTypes = false;
10980 }
10981
10982 if (allLTypes) return lhs;
10983 if (allRTypes) return rhs;
10984
10985 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
10986 EPI.ExtInfo = einfo;
10987 EPI.ExtParameterInfos =
10988 newParamInfos.empty() ? nullptr : newParamInfos.data();
10989 if (MergedFX)
10990 EPI.FunctionEffects = *MergedFX;
10991 return getFunctionType(retType, types, EPI);
10992 }
10993
10994 if (lproto) allRTypes = false;
10995 if (rproto) allLTypes = false;
10996
10997 const FunctionProtoType *proto = lproto ? lproto : rproto;
10998 if (proto) {
10999 assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here");
11000 if (proto->isVariadic())
11001 return {};
11002 // Check that the types are compatible with the types that
11003 // would result from default argument promotions (C99 6.7.5.3p15).
11004 // The only types actually affected are promotable integer
11005 // types and floats, which would be passed as a different
11006 // type depending on whether the prototype is visible.
11007 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
11008 QualType paramTy = proto->getParamType(i);
11009
11010 // Look at the converted type of enum types, since that is the type used
11011 // to pass enum values.
11012 if (const auto *Enum = paramTy->getAs<EnumType>()) {
11013 paramTy = Enum->getDecl()->getIntegerType();
11014 if (paramTy.isNull())
11015 return {};
11016 }
11017
11018 if (isPromotableIntegerType(paramTy) ||
11019 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
11020 return {};
11021 }
11022
11023 if (allLTypes) return lhs;
11024 if (allRTypes) return rhs;
11025
11027 EPI.ExtInfo = einfo;
11028 if (MergedFX)
11029 EPI.FunctionEffects = *MergedFX;
11030 return getFunctionType(retType, proto->getParamTypes(), EPI);
11031 }
11032
11033 if (allLTypes) return lhs;
11034 if (allRTypes) return rhs;
11035 return getFunctionNoProtoType(retType, einfo);
11036}
11037
11038/// Given that we have an enum type and a non-enum type, try to merge them.
11040 QualType other, bool isBlockReturnType) {
11041 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
11042 // a signed integer type, or an unsigned integer type.
11043 // Compatibility is based on the underlying type, not the promotion
11044 // type.
11045 QualType underlyingType = ET->getDecl()->getIntegerType();
11046 if (underlyingType.isNull())
11047 return {};
11048 if (Context.hasSameType(underlyingType, other))
11049 return other;
11050
11051 // In block return types, we're more permissive and accept any
11052 // integral type of the same size.
11053 if (isBlockReturnType && other->isIntegerType() &&
11054 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
11055 return other;
11056
11057 return {};
11058}
11059
11060QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
11061 bool Unqualified, bool BlockReturnType,
11062 bool IsConditionalOperator) {
11063 // For C++ we will not reach this code with reference types (see below),
11064 // for OpenMP variant call overloading we might.
11065 //
11066 // C++ [expr]: If an expression initially has the type "reference to T", the
11067 // type is adjusted to "T" prior to any further analysis, the expression
11068 // designates the object or function denoted by the reference, and the
11069 // expression is an lvalue unless the reference is an rvalue reference and
11070 // the expression is a function call (possibly inside parentheses).
11071 auto *LHSRefTy = LHS->getAs<ReferenceType>();
11072 auto *RHSRefTy = RHS->getAs<ReferenceType>();
11073 if (LangOpts.OpenMP && LHSRefTy && RHSRefTy &&
11074 LHS->getTypeClass() == RHS->getTypeClass())
11075 return mergeTypes(LHSRefTy->getPointeeType(), RHSRefTy->getPointeeType(),
11076 OfBlockPointer, Unqualified, BlockReturnType);
11077 if (LHSRefTy || RHSRefTy)
11078 return {};
11079
11080 if (Unqualified) {
11081 LHS = LHS.getUnqualifiedType();
11082 RHS = RHS.getUnqualifiedType();
11083 }
11084
11085 QualType LHSCan = getCanonicalType(LHS),
11086 RHSCan = getCanonicalType(RHS);
11087
11088 // If two types are identical, they are compatible.
11089 if (LHSCan == RHSCan)
11090 return LHS;
11091
11092 // If the qualifiers are different, the types aren't compatible... mostly.
11093 Qualifiers LQuals = LHSCan.getLocalQualifiers();
11094 Qualifiers RQuals = RHSCan.getLocalQualifiers();
11095 if (LQuals != RQuals) {
11096 // If any of these qualifiers are different, we have a type
11097 // mismatch.
11098 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
11099 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
11100 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
11101 LQuals.hasUnaligned() != RQuals.hasUnaligned())
11102 return {};
11103
11104 // Exactly one GC qualifier difference is allowed: __strong is
11105 // okay if the other type has no GC qualifier but is an Objective
11106 // C object pointer (i.e. implicitly strong by default). We fix
11107 // this by pretending that the unqualified type was actually
11108 // qualified __strong.
11109 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
11110 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
11111 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
11112
11113 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
11114 return {};
11115
11116 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
11118 }
11119 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
11121 }
11122 return {};
11123 }
11124
11125 // Okay, qualifiers are equal.
11126
11127 Type::TypeClass LHSClass = LHSCan->getTypeClass();
11128 Type::TypeClass RHSClass = RHSCan->getTypeClass();
11129
11130 // We want to consider the two function types to be the same for these
11131 // comparisons, just force one to the other.
11132 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
11133 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
11134
11135 // Same as above for arrays
11136 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
11137 LHSClass = Type::ConstantArray;
11138 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
11139 RHSClass = Type::ConstantArray;
11140
11141 // ObjCInterfaces are just specialized ObjCObjects.
11142 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
11143 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
11144
11145 // Canonicalize ExtVector -> Vector.
11146 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
11147 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
11148
11149 // If the canonical type classes don't match.
11150 if (LHSClass != RHSClass) {
11151 // Note that we only have special rules for turning block enum
11152 // returns into block int returns, not vice-versa.
11153 if (const auto *ETy = LHS->getAs<EnumType>()) {
11154 return mergeEnumWithInteger(*this, ETy, RHS, false);
11155 }
11156 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
11157 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
11158 }
11159 // allow block pointer type to match an 'id' type.
11160 if (OfBlockPointer && !BlockReturnType) {
11161 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
11162 return LHS;
11163 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
11164 return RHS;
11165 }
11166 // Allow __auto_type to match anything; it merges to the type with more
11167 // information.
11168 if (const auto *AT = LHS->getAs<AutoType>()) {
11169 if (!AT->isDeduced() && AT->isGNUAutoType())
11170 return RHS;
11171 }
11172 if (const auto *AT = RHS->getAs<AutoType>()) {
11173 if (!AT->isDeduced() && AT->isGNUAutoType())
11174 return LHS;
11175 }
11176 return {};
11177 }
11178
11179 // The canonical type classes match.
11180 switch (LHSClass) {
11181#define TYPE(Class, Base)
11182#define ABSTRACT_TYPE(Class, Base)
11183#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
11184#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
11185#define DEPENDENT_TYPE(Class, Base) case Type::Class:
11186#include "clang/AST/TypeNodes.inc"
11187 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
11188
11189 case Type::Auto:
11190 case Type::DeducedTemplateSpecialization:
11191 case Type::LValueReference:
11192 case Type::RValueReference:
11193 case Type::MemberPointer:
11194 llvm_unreachable("C++ should never be in mergeTypes");
11195
11196 case Type::ObjCInterface:
11197 case Type::IncompleteArray:
11198 case Type::VariableArray:
11199 case Type::FunctionProto:
11200 case Type::ExtVector:
11201 llvm_unreachable("Types are eliminated above");
11202
11203 case Type::Pointer:
11204 {
11205 // Merge two pointer types, while trying to preserve typedef info
11206 QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType();
11207 QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType();
11208 if (Unqualified) {
11209 LHSPointee = LHSPointee.getUnqualifiedType();
11210 RHSPointee = RHSPointee.getUnqualifiedType();
11211 }
11212 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
11213 Unqualified);
11214 if (ResultType.isNull())
11215 return {};
11216 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
11217 return LHS;
11218 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
11219 return RHS;
11220 return getPointerType(ResultType);
11221 }
11222 case Type::BlockPointer:
11223 {
11224 // Merge two block pointer types, while trying to preserve typedef info
11225 QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType();
11226 QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType();
11227 if (Unqualified) {
11228 LHSPointee = LHSPointee.getUnqualifiedType();
11229 RHSPointee = RHSPointee.getUnqualifiedType();
11230 }
11231 if (getLangOpts().OpenCL) {
11232 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
11233 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
11234 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
11235 // 6.12.5) thus the following check is asymmetric.
11236 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual))
11237 return {};
11238 LHSPteeQual.removeAddressSpace();
11239 RHSPteeQual.removeAddressSpace();
11240 LHSPointee =
11241 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
11242 RHSPointee =
11243 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
11244 }
11245 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
11246 Unqualified);
11247 if (ResultType.isNull())
11248 return {};
11249 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
11250 return LHS;
11251 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
11252 return RHS;
11253 return getBlockPointerType(ResultType);
11254 }
11255 case Type::Atomic:
11256 {
11257 // Merge two pointer types, while trying to preserve typedef info
11258 QualType LHSValue = LHS->castAs<AtomicType>()->getValueType();
11259 QualType RHSValue = RHS->castAs<AtomicType>()->getValueType();
11260 if (Unqualified) {
11261 LHSValue = LHSValue.getUnqualifiedType();
11262 RHSValue = RHSValue.getUnqualifiedType();
11263 }
11264 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
11265 Unqualified);
11266 if (ResultType.isNull())
11267 return {};
11268 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
11269 return LHS;
11270 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
11271 return RHS;
11272 return getAtomicType(ResultType);
11273 }
11274 case Type::ConstantArray:
11275 {
11276 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
11277 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
11278 if (LCAT && RCAT && RCAT->getZExtSize() != LCAT->getZExtSize())
11279 return {};
11280
11281 QualType LHSElem = getAsArrayType(LHS)->getElementType();
11282 QualType RHSElem = getAsArrayType(RHS)->getElementType();
11283 if (Unqualified) {
11284 LHSElem = LHSElem.getUnqualifiedType();
11285 RHSElem = RHSElem.getUnqualifiedType();
11286 }
11287
11288 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
11289 if (ResultType.isNull())
11290 return {};
11291
11292 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
11293 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
11294
11295 // If either side is a variable array, and both are complete, check whether
11296 // the current dimension is definite.
11297 if (LVAT || RVAT) {
11298 auto SizeFetch = [this](const VariableArrayType* VAT,
11299 const ConstantArrayType* CAT)
11300 -> std::pair<bool,llvm::APInt> {
11301 if (VAT) {
11302 std::optional<llvm::APSInt> TheInt;
11303 Expr *E = VAT->getSizeExpr();
11304 if (E && (TheInt = E->getIntegerConstantExpr(*this)))
11305 return std::make_pair(true, *TheInt);
11306 return std::make_pair(false, llvm::APSInt());
11307 }
11308 if (CAT)
11309 return std::make_pair(true, CAT->getSize());
11310 return std::make_pair(false, llvm::APInt());
11311 };
11312
11313 bool HaveLSize, HaveRSize;
11314 llvm::APInt LSize, RSize;
11315 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
11316 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
11317 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
11318 return {}; // Definite, but unequal, array dimension
11319 }
11320
11321 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
11322 return LHS;
11323 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
11324 return RHS;
11325 if (LCAT)
11326 return getConstantArrayType(ResultType, LCAT->getSize(),
11327 LCAT->getSizeExpr(), ArraySizeModifier(), 0);
11328 if (RCAT)
11329 return getConstantArrayType(ResultType, RCAT->getSize(),
11330 RCAT->getSizeExpr(), ArraySizeModifier(), 0);
11331 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
11332 return LHS;
11333 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
11334 return RHS;
11335 if (LVAT) {
11336 // FIXME: This isn't correct! But tricky to implement because
11337 // the array's size has to be the size of LHS, but the type
11338 // has to be different.
11339 return LHS;
11340 }
11341 if (RVAT) {
11342 // FIXME: This isn't correct! But tricky to implement because
11343 // the array's size has to be the size of RHS, but the type
11344 // has to be different.
11345 return RHS;
11346 }
11347 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
11348 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
11349 return getIncompleteArrayType(ResultType, ArraySizeModifier(), 0);
11350 }
11351 case Type::FunctionNoProto:
11352 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified,
11353 /*AllowCXX=*/false, IsConditionalOperator);
11354 case Type::Record:
11355 case Type::Enum:
11356 return {};
11357 case Type::Builtin:
11358 // Only exactly equal builtin types are compatible, which is tested above.
11359 return {};
11360 case Type::Complex:
11361 // Distinct complex types are incompatible.
11362 return {};
11363 case Type::Vector:
11364 // FIXME: The merged type should be an ExtVector!
11365 if (areCompatVectorTypes(LHSCan->castAs<VectorType>(),
11366 RHSCan->castAs<VectorType>()))
11367 return LHS;
11368 return {};
11369 case Type::ConstantMatrix:
11371 RHSCan->castAs<ConstantMatrixType>()))
11372 return LHS;
11373 return {};
11374 case Type::ObjCObject: {
11375 // Check if the types are assignment compatible.
11376 // FIXME: This should be type compatibility, e.g. whether
11377 // "LHS x; RHS x;" at global scope is legal.
11379 RHS->castAs<ObjCObjectType>()))
11380 return LHS;
11381 return {};
11382 }
11383 case Type::ObjCObjectPointer:
11384 if (OfBlockPointer) {
11387 RHS->castAs<ObjCObjectPointerType>(), BlockReturnType))
11388 return LHS;
11389 return {};
11390 }
11393 return LHS;
11394 return {};
11395 case Type::Pipe:
11396 assert(LHS != RHS &&
11397 "Equivalent pipe types should have already been handled!");
11398 return {};
11399 case Type::ArrayParameter:
11400 assert(LHS != RHS &&
11401 "Equivalent ArrayParameter types should have already been handled!");
11402 return {};
11403 case Type::BitInt: {
11404 // Merge two bit-precise int types, while trying to preserve typedef info.
11405 bool LHSUnsigned = LHS->castAs<BitIntType>()->isUnsigned();
11406 bool RHSUnsigned = RHS->castAs<BitIntType>()->isUnsigned();
11407 unsigned LHSBits = LHS->castAs<BitIntType>()->getNumBits();
11408 unsigned RHSBits = RHS->castAs<BitIntType>()->getNumBits();
11409
11410 // Like unsigned/int, shouldn't have a type if they don't match.
11411 if (LHSUnsigned != RHSUnsigned)
11412 return {};
11413
11414 if (LHSBits != RHSBits)
11415 return {};
11416 return LHS;
11417 }
11418 }
11419
11420 llvm_unreachable("Invalid Type::Class!");
11421}
11422
11424 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
11425 bool &CanUseFirst, bool &CanUseSecond,
11427 assert(NewParamInfos.empty() && "param info list not empty");
11428 CanUseFirst = CanUseSecond = true;
11429 bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
11430 bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
11431
11432 // Fast path: if the first type doesn't have ext parameter infos,
11433 // we match if and only if the second type also doesn't have them.
11434 if (!FirstHasInfo && !SecondHasInfo)
11435 return true;
11436
11437 bool NeedParamInfo = false;
11438 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
11439 : SecondFnType->getExtParameterInfos().size();
11440
11441 for (size_t I = 0; I < E; ++I) {
11442 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
11443 if (FirstHasInfo)
11444 FirstParam = FirstFnType->getExtParameterInfo(I);
11445 if (SecondHasInfo)
11446 SecondParam = SecondFnType->getExtParameterInfo(I);
11447
11448 // Cannot merge unless everything except the noescape flag matches.
11449 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
11450 return false;
11451
11452 bool FirstNoEscape = FirstParam.isNoEscape();
11453 bool SecondNoEscape = SecondParam.isNoEscape();
11454 bool IsNoEscape = FirstNoEscape && SecondNoEscape;
11455 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
11456 if (NewParamInfos.back().getOpaqueValue())
11457 NeedParamInfo = true;
11458 if (FirstNoEscape != IsNoEscape)
11459 CanUseFirst = false;
11460 if (SecondNoEscape != IsNoEscape)
11461 CanUseSecond = false;
11462 }
11463
11464 if (!NeedParamInfo)
11465 NewParamInfos.clear();
11466
11467 return true;
11468}
11469
11471 ObjCLayouts[CD] = nullptr;
11472}
11473
11474/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
11475/// 'RHS' attributes and returns the merged version; including for function
11476/// return types.
11478 QualType LHSCan = getCanonicalType(LHS),
11479 RHSCan = getCanonicalType(RHS);
11480 // If two types are identical, they are compatible.
11481 if (LHSCan == RHSCan)
11482 return LHS;
11483 if (RHSCan->isFunctionType()) {
11484 if (!LHSCan->isFunctionType())
11485 return {};
11486 QualType OldReturnType =
11487 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
11488 QualType NewReturnType =
11489 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
11490 QualType ResReturnType =
11491 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
11492 if (ResReturnType.isNull())
11493 return {};
11494 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
11495 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
11496 // In either case, use OldReturnType to build the new function type.
11497 const auto *F = LHS->castAs<FunctionType>();
11498 if (const auto *FPT = cast<FunctionProtoType>(F)) {
11499 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11500 EPI.ExtInfo = getFunctionExtInfo(LHS);
11501 QualType ResultType =
11502 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
11503 return ResultType;
11504 }
11505 }
11506 return {};
11507 }
11508
11509 // If the qualifiers are different, the types can still be merged.
11510 Qualifiers LQuals = LHSCan.getLocalQualifiers();
11511 Qualifiers RQuals = RHSCan.getLocalQualifiers();
11512 if (LQuals != RQuals) {
11513 // If any of these qualifiers are different, we have a type mismatch.
11514 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
11515 LQuals.getAddressSpace() != RQuals.getAddressSpace())
11516 return {};
11517
11518 // Exactly one GC qualifier difference is allowed: __strong is
11519 // okay if the other type has no GC qualifier but is an Objective
11520 // C object pointer (i.e. implicitly strong by default). We fix
11521 // this by pretending that the unqualified type was actually
11522 // qualified __strong.
11523 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
11524 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
11525 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
11526
11527 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
11528 return {};
11529
11530 if (GC_L == Qualifiers::Strong)
11531 return LHS;
11532 if (GC_R == Qualifiers::Strong)
11533 return RHS;
11534 return {};
11535 }
11536
11537 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
11538 QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType();
11539 QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType();
11540 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
11541 if (ResQT == LHSBaseQT)
11542 return LHS;
11543 if (ResQT == RHSBaseQT)
11544 return RHS;
11545 }
11546 return {};
11547}
11548
11549//===----------------------------------------------------------------------===//
11550// Integer Predicates
11551//===----------------------------------------------------------------------===//
11552
11554 if (const auto *ET = T->getAs<EnumType>())
11555 T = ET->getDecl()->getIntegerType();
11556 if (T->isBooleanType())
11557 return 1;
11558 if (const auto *EIT = T->getAs<BitIntType>())
11559 return EIT->getNumBits();
11560 // For builtin types, just use the standard type sizing method
11561 return (unsigned)getTypeSize(T);
11562}
11563
11565 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
11566 T->isFixedPointType()) &&
11567 "Unexpected type");
11568
11569 // Turn <4 x signed int> -> <4 x unsigned int>
11570 if (const auto *VTy = T->getAs<VectorType>())
11571 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
11572 VTy->getNumElements(), VTy->getVectorKind());
11573
11574 // For _BitInt, return an unsigned _BitInt with same width.
11575 if (const auto *EITy = T->getAs<BitIntType>())
11576 return getBitIntType(/*Unsigned=*/true, EITy->getNumBits());
11577
11578 // For enums, get the underlying integer type of the enum, and let the general
11579 // integer type signchanging code handle it.
11580 if (const auto *ETy = T->getAs<EnumType>())
11581 T = ETy->getDecl()->getIntegerType();
11582
11583 switch (T->castAs<BuiltinType>()->getKind()) {
11584 case BuiltinType::Char_U:
11585 // Plain `char` is mapped to `unsigned char` even if it's already unsigned
11586 case BuiltinType::Char_S:
11587 case BuiltinType::SChar:
11588 case BuiltinType::Char8:
11589 return UnsignedCharTy;
11590 case BuiltinType::Short:
11591 return UnsignedShortTy;
11592 case BuiltinType::Int:
11593 return UnsignedIntTy;
11594 case BuiltinType::Long:
11595 return UnsignedLongTy;
11596 case BuiltinType::LongLong:
11597 return UnsignedLongLongTy;
11598 case BuiltinType::Int128:
11599 return UnsignedInt128Ty;
11600 // wchar_t is special. It is either signed or not, but when it's signed,
11601 // there's no matching "unsigned wchar_t". Therefore we return the unsigned
11602 // version of its underlying type instead.
11603 case BuiltinType::WChar_S:
11604 return getUnsignedWCharType();
11605
11606 case BuiltinType::ShortAccum:
11607 return UnsignedShortAccumTy;
11608 case BuiltinType::Accum:
11609 return UnsignedAccumTy;
11610 case BuiltinType::LongAccum:
11611 return UnsignedLongAccumTy;
11612 case BuiltinType::SatShortAccum:
11614 case BuiltinType::SatAccum:
11615 return SatUnsignedAccumTy;
11616 case BuiltinType::SatLongAccum:
11618 case BuiltinType::ShortFract:
11619 return UnsignedShortFractTy;
11620 case BuiltinType::Fract:
11621 return UnsignedFractTy;
11622 case BuiltinType::LongFract:
11623 return UnsignedLongFractTy;
11624 case BuiltinType::SatShortFract:
11626 case BuiltinType::SatFract:
11627 return SatUnsignedFractTy;
11628 case BuiltinType::SatLongFract:
11630 default:
11633 "Unexpected signed integer or fixed point type");
11634 return T;
11635 }
11636}
11637
11639 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
11640 T->isFixedPointType()) &&
11641 "Unexpected type");
11642
11643 // Turn <4 x unsigned int> -> <4 x signed int>
11644 if (const auto *VTy = T->getAs<VectorType>())
11645 return getVectorType(getCorrespondingSignedType(VTy->getElementType()),
11646 VTy->getNumElements(), VTy->getVectorKind());
11647
11648 // For _BitInt, return a signed _BitInt with same width.
11649 if (const auto *EITy = T->getAs<BitIntType>())
11650 return getBitIntType(/*Unsigned=*/false, EITy->getNumBits());
11651
11652 // For enums, get the underlying integer type of the enum, and let the general
11653 // integer type signchanging code handle it.
11654 if (const auto *ETy = T->getAs<EnumType>())
11655 T = ETy->getDecl()->getIntegerType();
11656
11657 switch (T->castAs<BuiltinType>()->getKind()) {
11658 case BuiltinType::Char_S:
11659 // Plain `char` is mapped to `signed char` even if it's already signed
11660 case BuiltinType::Char_U:
11661 case BuiltinType::UChar:
11662 case BuiltinType::Char8:
11663 return SignedCharTy;
11664 case BuiltinType::UShort:
11665 return ShortTy;
11666 case BuiltinType::UInt:
11667 return IntTy;
11668 case BuiltinType::ULong:
11669 return LongTy;
11670 case BuiltinType::ULongLong:
11671 return LongLongTy;
11672 case BuiltinType::UInt128:
11673 return Int128Ty;
11674 // wchar_t is special. It is either unsigned or not, but when it's unsigned,
11675 // there's no matching "signed wchar_t". Therefore we return the signed
11676 // version of its underlying type instead.
11677 case BuiltinType::WChar_U:
11678 return getSignedWCharType();
11679
11680 case BuiltinType::UShortAccum:
11681 return ShortAccumTy;
11682 case BuiltinType::UAccum:
11683 return AccumTy;
11684 case BuiltinType::ULongAccum:
11685 return LongAccumTy;
11686 case BuiltinType::SatUShortAccum:
11687 return SatShortAccumTy;
11688 case BuiltinType::SatUAccum:
11689 return SatAccumTy;
11690 case BuiltinType::SatULongAccum:
11691 return SatLongAccumTy;
11692 case BuiltinType::UShortFract:
11693 return ShortFractTy;
11694 case BuiltinType::UFract:
11695 return FractTy;
11696 case BuiltinType::ULongFract:
11697 return LongFractTy;
11698 case BuiltinType::SatUShortFract:
11699 return SatShortFractTy;
11700 case BuiltinType::SatUFract:
11701 return SatFractTy;
11702 case BuiltinType::SatULongFract:
11703 return SatLongFractTy;
11704 default:
11705 assert(
11707 "Unexpected signed integer or fixed point type");
11708 return T;
11709 }
11710}
11711
11713
11715 QualType ReturnType) {}
11716
11717//===----------------------------------------------------------------------===//
11718// Builtin Type Computation
11719//===----------------------------------------------------------------------===//
11720
11721/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
11722/// pointer over the consumed characters. This returns the resultant type. If
11723/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
11724/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
11725/// a vector of "i*".
11726///
11727/// RequiresICE is filled in on return to indicate whether the value is required
11728/// to be an Integer Constant Expression.
11729static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
11731 bool &RequiresICE,
11732 bool AllowTypeModifiers) {
11733 // Modifiers.
11734 int HowLong = 0;
11735 bool Signed = false, Unsigned = false;
11736 RequiresICE = false;
11737
11738 // Read the prefixed modifiers first.
11739 bool Done = false;
11740 #ifndef NDEBUG
11741 bool IsSpecial = false;
11742 #endif
11743 while (!Done) {
11744 switch (*Str++) {
11745 default: Done = true; --Str; break;
11746 case 'I':
11747 RequiresICE = true;
11748 break;
11749 case 'S':
11750 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
11751 assert(!Signed && "Can't use 'S' modifier multiple times!");
11752 Signed = true;
11753 break;
11754 case 'U':
11755 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
11756 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
11757 Unsigned = true;
11758 break;
11759 case 'L':
11760 assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers");
11761 assert(HowLong <= 2 && "Can't have LLLL modifier");
11762 ++HowLong;
11763 break;
11764 case 'N':
11765 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
11766 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
11767 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
11768 #ifndef NDEBUG
11769 IsSpecial = true;
11770 #endif
11771 if (Context.getTargetInfo().getLongWidth() == 32)
11772 ++HowLong;
11773 break;
11774 case 'W':
11775 // This modifier represents int64 type.
11776 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
11777 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
11778 #ifndef NDEBUG
11779 IsSpecial = true;
11780 #endif
11781 switch (Context.getTargetInfo().getInt64Type()) {
11782 default:
11783 llvm_unreachable("Unexpected integer type");
11785 HowLong = 1;
11786 break;
11788 HowLong = 2;
11789 break;
11790 }
11791 break;
11792 case 'Z':
11793 // This modifier represents int32 type.
11794 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
11795 assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
11796 #ifndef NDEBUG
11797 IsSpecial = true;
11798 #endif
11799 switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) {
11800 default:
11801 llvm_unreachable("Unexpected integer type");
11803 HowLong = 0;
11804 break;
11806 HowLong = 1;
11807 break;
11809 HowLong = 2;
11810 break;
11811 }
11812 break;
11813 case 'O':
11814 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
11815 assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
11816 #ifndef NDEBUG
11817 IsSpecial = true;
11818 #endif
11819 if (Context.getLangOpts().OpenCL)
11820 HowLong = 1;
11821 else
11822 HowLong = 2;
11823 break;
11824 }
11825 }
11826
11827 QualType Type;
11828
11829 // Read the base type.
11830 switch (*Str++) {
11831 default: llvm_unreachable("Unknown builtin type letter!");
11832 case 'x':
11833 assert(HowLong == 0 && !Signed && !Unsigned &&
11834 "Bad modifiers used with 'x'!");
11835 Type = Context.Float16Ty;
11836 break;
11837 case 'y':
11838 assert(HowLong == 0 && !Signed && !Unsigned &&
11839 "Bad modifiers used with 'y'!");
11840 Type = Context.BFloat16Ty;
11841 break;
11842 case 'v':
11843 assert(HowLong == 0 && !Signed && !Unsigned &&
11844 "Bad modifiers used with 'v'!");
11845 Type = Context.VoidTy;
11846 break;
11847 case 'h':
11848 assert(HowLong == 0 && !Signed && !Unsigned &&
11849 "Bad modifiers used with 'h'!");
11850 Type = Context.HalfTy;
11851 break;
11852 case 'f':
11853 assert(HowLong == 0 && !Signed && !Unsigned &&
11854 "Bad modifiers used with 'f'!");
11855 Type = Context.FloatTy;
11856 break;
11857 case 'd':
11858 assert(HowLong < 3 && !Signed && !Unsigned &&
11859 "Bad modifiers used with 'd'!");
11860 if (HowLong == 1)
11861 Type = Context.LongDoubleTy;
11862 else if (HowLong == 2)
11863 Type = Context.Float128Ty;
11864 else
11865 Type = Context.DoubleTy;
11866 break;
11867 case 's':
11868 assert(HowLong == 0 && "Bad modifiers used with 's'!");
11869 if (Unsigned)
11870 Type = Context.UnsignedShortTy;
11871 else
11872 Type = Context.ShortTy;
11873 break;
11874 case 'i':
11875 if (HowLong == 3)
11876 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
11877 else if (HowLong == 2)
11878 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
11879 else if (HowLong == 1)
11880 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
11881 else
11882 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
11883 break;
11884 case 'c':
11885 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
11886 if (Signed)
11887 Type = Context.SignedCharTy;
11888 else if (Unsigned)
11889 Type = Context.UnsignedCharTy;
11890 else
11891 Type = Context.CharTy;
11892 break;
11893 case 'b': // boolean
11894 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
11895 Type = Context.BoolTy;
11896 break;
11897 case 'z': // size_t.
11898 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
11899 Type = Context.getSizeType();
11900 break;
11901 case 'w': // wchar_t.
11902 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
11903 Type = Context.getWideCharType();
11904 break;
11905 case 'F':
11906 Type = Context.getCFConstantStringType();
11907 break;
11908 case 'G':
11909 Type = Context.getObjCIdType();
11910 break;
11911 case 'H':
11912 Type = Context.getObjCSelType();
11913 break;
11914 case 'M':
11915 Type = Context.getObjCSuperType();
11916 break;
11917 case 'a':
11918 Type = Context.getBuiltinVaListType();
11919 assert(!Type.isNull() && "builtin va list type not initialized!");
11920 break;
11921 case 'A':
11922 // This is a "reference" to a va_list; however, what exactly
11923 // this means depends on how va_list is defined. There are two
11924 // different kinds of va_list: ones passed by value, and ones
11925 // passed by reference. An example of a by-value va_list is
11926 // x86, where va_list is a char*. An example of by-ref va_list
11927 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
11928 // we want this argument to be a char*&; for x86-64, we want
11929 // it to be a __va_list_tag*.
11930 Type = Context.getBuiltinVaListType();
11931 assert(!Type.isNull() && "builtin va list type not initialized!");
11932 if (Type->isArrayType())
11933 Type = Context.getArrayDecayedType(Type);
11934 else
11935 Type = Context.getLValueReferenceType(Type);
11936 break;
11937 case 'q': {
11938 char *End;
11939 unsigned NumElements = strtoul(Str, &End, 10);
11940 assert(End != Str && "Missing vector size");
11941 Str = End;
11942
11943 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
11944 RequiresICE, false);
11945 assert(!RequiresICE && "Can't require vector ICE");
11946
11947 Type = Context.getScalableVectorType(ElementType, NumElements);
11948 break;
11949 }
11950 case 'Q': {
11951 switch (*Str++) {
11952 case 'a': {
11953 Type = Context.SveCountTy;
11954 break;
11955 }
11956 case 'b': {
11957 Type = Context.AMDGPUBufferRsrcTy;
11958 break;
11959 }
11960 default:
11961 llvm_unreachable("Unexpected target builtin type");
11962 }
11963 break;
11964 }
11965 case 'V': {
11966 char *End;
11967 unsigned NumElements = strtoul(Str, &End, 10);
11968 assert(End != Str && "Missing vector size");
11969 Str = End;
11970
11971 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
11972 RequiresICE, false);
11973 assert(!RequiresICE && "Can't require vector ICE");
11974
11975 // TODO: No way to make AltiVec vectors in builtins yet.
11976 Type = Context.getVectorType(ElementType, NumElements, VectorKind::Generic);
11977 break;
11978 }
11979 case 'E': {
11980 char *End;
11981
11982 unsigned NumElements = strtoul(Str, &End, 10);
11983 assert(End != Str && "Missing vector size");
11984
11985 Str = End;
11986
11987 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
11988 false);
11989 Type = Context.getExtVectorType(ElementType, NumElements);
11990 break;
11991 }
11992 case 'X': {
11993 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
11994 false);
11995 assert(!RequiresICE && "Can't require complex ICE");
11996 Type = Context.getComplexType(ElementType);
11997 break;
11998 }
11999 case 'Y':
12000 Type = Context.getPointerDiffType();
12001 break;
12002 case 'P':
12003 Type = Context.getFILEType();
12004 if (Type.isNull()) {
12006 return {};
12007 }
12008 break;
12009 case 'J':
12010 if (Signed)
12011 Type = Context.getsigjmp_bufType();
12012 else
12013 Type = Context.getjmp_bufType();
12014
12015 if (Type.isNull()) {
12017 return {};
12018 }
12019 break;
12020 case 'K':
12021 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
12022 Type = Context.getucontext_tType();
12023
12024 if (Type.isNull()) {
12026 return {};
12027 }
12028 break;
12029 case 'p':
12030 Type = Context.getProcessIDType();
12031 break;
12032 }
12033
12034 // If there are modifiers and if we're allowed to parse them, go for it.
12035 Done = !AllowTypeModifiers;
12036 while (!Done) {
12037 switch (char c = *Str++) {
12038 default: Done = true; --Str; break;
12039 case '*':
12040 case '&': {
12041 // Both pointers and references can have their pointee types
12042 // qualified with an address space.
12043 char *End;
12044 unsigned AddrSpace = strtoul(Str, &End, 10);
12045 if (End != Str) {
12046 // Note AddrSpace == 0 is not the same as an unspecified address space.
12047 Type = Context.getAddrSpaceQualType(
12048 Type,
12049 Context.getLangASForBuiltinAddressSpace(AddrSpace));
12050 Str = End;
12051 }
12052 if (c == '*')
12053 Type = Context.getPointerType(Type);
12054 else
12055 Type = Context.getLValueReferenceType(Type);
12056 break;
12057 }
12058 // FIXME: There's no way to have a built-in with an rvalue ref arg.
12059 case 'C':
12060 Type = Type.withConst();
12061 break;
12062 case 'D':
12063 Type = Context.getVolatileType(Type);
12064 break;
12065 case 'R':
12066 Type = Type.withRestrict();
12067 break;
12068 }
12069 }
12070
12071 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
12072 "Integer constant 'I' type must be an integer");
12073
12074 return Type;
12075}
12076
12077// On some targets such as PowerPC, some of the builtins are defined with custom
12078// type descriptors for target-dependent types. These descriptors are decoded in
12079// other functions, but it may be useful to be able to fall back to default
12080// descriptor decoding to define builtins mixing target-dependent and target-
12081// independent types. This function allows decoding one type descriptor with
12082// default decoding.
12083QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context,
12084 GetBuiltinTypeError &Error, bool &RequireICE,
12085 bool AllowTypeModifiers) const {
12086 return DecodeTypeFromStr(Str, Context, Error, RequireICE, AllowTypeModifiers);
12087}
12088
12089/// GetBuiltinType - Return the type for the specified builtin.
12091 GetBuiltinTypeError &Error,
12092 unsigned *IntegerConstantArgs) const {
12093 const char *TypeStr = BuiltinInfo.getTypeString(Id);
12094 if (TypeStr[0] == '\0') {
12095 Error = GE_Missing_type;
12096 return {};
12097 }
12098
12099 SmallVector<QualType, 8> ArgTypes;
12100
12101 bool RequiresICE = false;
12102 Error = GE_None;
12103 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
12104 RequiresICE, true);
12105 if (Error != GE_None)
12106 return {};
12107
12108 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
12109
12110 while (TypeStr[0] && TypeStr[0] != '.') {
12111 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
12112 if (Error != GE_None)
12113 return {};
12114
12115 // If this argument is required to be an IntegerConstantExpression and the
12116 // caller cares, fill in the bitmask we return.
12117 if (RequiresICE && IntegerConstantArgs)
12118 *IntegerConstantArgs |= 1 << ArgTypes.size();
12119
12120 // Do array -> pointer decay. The builtin should use the decayed type.
12121 if (Ty->isArrayType())
12122 Ty = getArrayDecayedType(Ty);
12123
12124 ArgTypes.push_back(Ty);
12125 }
12126
12127 if (Id == Builtin::BI__GetExceptionInfo)
12128 return {};
12129
12130 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
12131 "'.' should only occur at end of builtin type list!");
12132
12133 bool Variadic = (TypeStr[0] == '.');
12134
12136 Variadic, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
12137 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
12138
12139
12140 // We really shouldn't be making a no-proto type here.
12141 if (ArgTypes.empty() && Variadic && !getLangOpts().requiresStrictPrototypes())
12142 return getFunctionNoProtoType(ResType, EI);
12143
12145 EPI.ExtInfo = EI;
12146 EPI.Variadic = Variadic;
12148 EPI.ExceptionSpec.Type =
12150
12151 return getFunctionType(ResType, ArgTypes, EPI);
12152}
12153
12155 const FunctionDecl *FD) {
12156 if (!FD->isExternallyVisible())
12157 return GVA_Internal;
12158
12159 // Non-user-provided functions get emitted as weak definitions with every
12160 // use, no matter whether they've been explicitly instantiated etc.
12161 if (!FD->isUserProvided())
12162 return GVA_DiscardableODR;
12163
12165 switch (FD->getTemplateSpecializationKind()) {
12166 case TSK_Undeclared:
12169 break;
12170
12172 return GVA_StrongODR;
12173
12174 // C++11 [temp.explicit]p10:
12175 // [ Note: The intent is that an inline function that is the subject of
12176 // an explicit instantiation declaration will still be implicitly
12177 // instantiated when used so that the body can be considered for
12178 // inlining, but that no out-of-line copy of the inline function would be
12179 // generated in the translation unit. -- end note ]
12182
12185 break;
12186 }
12187
12188 if (!FD->isInlined())
12189 return External;
12190
12191 if ((!Context.getLangOpts().CPlusPlus &&
12192 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12193 !FD->hasAttr<DLLExportAttr>()) ||
12194 FD->hasAttr<GNUInlineAttr>()) {
12195 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
12196
12197 // GNU or C99 inline semantics. Determine whether this symbol should be
12198 // externally visible.
12200 return External;
12201
12202 // C99 inline semantics, where the symbol is not externally visible.
12204 }
12205
12206 // Functions specified with extern and inline in -fms-compatibility mode
12207 // forcibly get emitted. While the body of the function cannot be later
12208 // replaced, the function definition cannot be discarded.
12209 if (FD->isMSExternInline())
12210 return GVA_StrongODR;
12211
12212 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12213 isa<CXXConstructorDecl>(FD) &&
12214 cast<CXXConstructorDecl>(FD)->isInheritingConstructor())
12215 // Our approach to inheriting constructors is fundamentally different from
12216 // that used by the MS ABI, so keep our inheriting constructor thunks
12217 // internal rather than trying to pick an unambiguous mangling for them.
12218 return GVA_Internal;
12219
12220 return GVA_DiscardableODR;
12221}
12222
12224 const Decl *D, GVALinkage L) {
12225 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
12226 // dllexport/dllimport on inline functions.
12227 if (D->hasAttr<DLLImportAttr>()) {
12228 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
12230 } else if (D->hasAttr<DLLExportAttr>()) {
12231 if (L == GVA_DiscardableODR)
12232 return GVA_StrongODR;
12233 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) {
12234 // Device-side functions with __global__ attribute must always be
12235 // visible externally so they can be launched from host.
12236 if (D->hasAttr<CUDAGlobalAttr>() &&
12237 (L == GVA_DiscardableODR || L == GVA_Internal))
12238 return GVA_StrongODR;
12239 // Single source offloading languages like CUDA/HIP need to be able to
12240 // access static device variables from host code of the same compilation
12241 // unit. This is done by externalizing the static variable with a shared
12242 // name between the host and device compilation which is the same for the
12243 // same compilation unit whereas different among different compilation
12244 // units.
12245 if (Context.shouldExternalize(D))
12246 return GVA_StrongExternal;
12247 }
12248 return L;
12249}
12250
12251/// Adjust the GVALinkage for a declaration based on what an external AST source
12252/// knows about whether there can be other definitions of this declaration.
12253static GVALinkage
12255 GVALinkage L) {
12256 ExternalASTSource *Source = Ctx.getExternalSource();
12257 if (!Source)
12258 return L;
12259
12260 switch (Source->hasExternalDefinitions(D)) {
12262 // Other translation units rely on us to provide the definition.
12263 if (L == GVA_DiscardableODR)
12264 return GVA_StrongODR;
12265 break;
12266
12269
12271 break;
12272 }
12273 return L;
12274}
12275
12279 basicGVALinkageForFunction(*this, FD)));
12280}
12281
12283 const VarDecl *VD) {
12284 // As an extension for interactive REPLs, make sure constant variables are
12285 // only emitted once instead of LinkageComputer::getLVForNamespaceScopeDecl
12286 // marking them as internal.
12287 if (Context.getLangOpts().CPlusPlus &&
12288 Context.getLangOpts().IncrementalExtensions &&
12289 VD->getType().isConstQualified() &&
12290 !VD->getType().isVolatileQualified() && !VD->isInline() &&
12291 !isa<VarTemplateSpecializationDecl>(VD) && !VD->getDescribedVarTemplate())
12292 return GVA_DiscardableODR;
12293
12294 if (!VD->isExternallyVisible())
12295 return GVA_Internal;
12296
12297 if (VD->isStaticLocal()) {
12298 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
12299 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
12300 LexicalContext = LexicalContext->getLexicalParent();
12301
12302 // ObjC Blocks can create local variables that don't have a FunctionDecl
12303 // LexicalContext.
12304 if (!LexicalContext)
12305 return GVA_DiscardableODR;
12306
12307 // Otherwise, let the static local variable inherit its linkage from the
12308 // nearest enclosing function.
12309 auto StaticLocalLinkage =
12310 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
12311
12312 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
12313 // be emitted in any object with references to the symbol for the object it
12314 // contains, whether inline or out-of-line."
12315 // Similar behavior is observed with MSVC. An alternative ABI could use
12316 // StrongODR/AvailableExternally to match the function, but none are
12317 // known/supported currently.
12318 if (StaticLocalLinkage == GVA_StrongODR ||
12319 StaticLocalLinkage == GVA_AvailableExternally)
12320 return GVA_DiscardableODR;
12321 return StaticLocalLinkage;
12322 }
12323
12324 // MSVC treats in-class initialized static data members as definitions.
12325 // By giving them non-strong linkage, out-of-line definitions won't
12326 // cause link errors.
12328 return GVA_DiscardableODR;
12329
12330 // Most non-template variables have strong linkage; inline variables are
12331 // linkonce_odr or (occasionally, for compatibility) weak_odr.
12332 GVALinkage StrongLinkage;
12333 switch (Context.getInlineVariableDefinitionKind(VD)) {
12335 StrongLinkage = GVA_StrongExternal;
12336 break;
12339 StrongLinkage = GVA_DiscardableODR;
12340 break;
12342 StrongLinkage = GVA_StrongODR;
12343 break;
12344 }
12345
12346 switch (VD->getTemplateSpecializationKind()) {
12347 case TSK_Undeclared:
12348 return StrongLinkage;
12349
12351 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12352 VD->isStaticDataMember()
12354 : StrongLinkage;
12355
12357 return GVA_StrongODR;
12358
12361
12363 return GVA_DiscardableODR;
12364 }
12365
12366 llvm_unreachable("Invalid Linkage!");
12367}
12368
12372 basicGVALinkageForVariable(*this, VD)));
12373}
12374
12376 if (const auto *VD = dyn_cast<VarDecl>(D)) {
12377 if (!VD->isFileVarDecl())
12378 return false;
12379 // Global named register variables (GNU extension) are never emitted.
12380 if (VD->getStorageClass() == SC_Register)
12381 return false;
12382 if (VD->getDescribedVarTemplate() ||
12383 isa<VarTemplatePartialSpecializationDecl>(VD))
12384 return false;
12385 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
12386 // We never need to emit an uninstantiated function template.
12387 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
12388 return false;
12389 } else if (isa<PragmaCommentDecl>(D))
12390 return true;
12391 else if (isa<PragmaDetectMismatchDecl>(D))
12392 return true;
12393 else if (isa<OMPRequiresDecl>(D))
12394 return true;
12395 else if (isa<OMPThreadPrivateDecl>(D))
12396 return !D->getDeclContext()->isDependentContext();
12397 else if (isa<OMPAllocateDecl>(D))
12398 return !D->getDeclContext()->isDependentContext();
12399 else if (isa<OMPDeclareReductionDecl>(D) || isa<OMPDeclareMapperDecl>(D))
12400 return !D->getDeclContext()->isDependentContext();
12401 else if (isa<ImportDecl>(D))
12402 return true;
12403 else
12404 return false;
12405
12406 // If this is a member of a class template, we do not need to emit it.
12408 return false;
12409
12410 // Weak references don't produce any output by themselves.
12411 if (D->hasAttr<WeakRefAttr>())
12412 return false;
12413
12414 // Aliases and used decls are required.
12415 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
12416 return true;
12417
12418 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
12419 // Forward declarations aren't required.
12420 if (!FD->doesThisDeclarationHaveABody())
12421 return FD->doesDeclarationForceExternallyVisibleDefinition();
12422
12423 // Constructors and destructors are required.
12424 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
12425 return true;
12426
12427 // The key function for a class is required. This rule only comes
12428 // into play when inline functions can be key functions, though.
12429 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
12430 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
12431 const CXXRecordDecl *RD = MD->getParent();
12432 if (MD->isOutOfLine() && RD->isDynamicClass()) {
12433 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
12434 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
12435 return true;
12436 }
12437 }
12438 }
12439
12441
12442 // static, static inline, always_inline, and extern inline functions can
12443 // always be deferred. Normal inline functions can be deferred in C99/C++.
12444 // Implicit template instantiations can also be deferred in C++.
12446 }
12447
12448 const auto *VD = cast<VarDecl>(D);
12449 assert(VD->isFileVarDecl() && "Expected file scoped var");
12450
12451 // If the decl is marked as `declare target to`, it should be emitted for the
12452 // host and for the device.
12453 if (LangOpts.OpenMP &&
12454 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
12455 return true;
12456
12457 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
12459 return false;
12460
12461 if (VD->shouldEmitInExternalSource())
12462 return false;
12463
12464 // Variables that can be needed in other TUs are required.
12467 return true;
12468
12469 // We never need to emit a variable that is available in another TU.
12471 return false;
12472
12473 // Variables that have destruction with side-effects are required.
12474 if (VD->needsDestruction(*this))
12475 return true;
12476
12477 // Variables that have initialization with side-effects are required.
12478 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
12479 // We can get a value-dependent initializer during error recovery.
12480 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
12481 return true;
12482
12483 // Likewise, variables with tuple-like bindings are required if their
12484 // bindings have side-effects.
12485 if (const auto *DD = dyn_cast<DecompositionDecl>(VD))
12486 for (const auto *BD : DD->bindings())
12487 if (const auto *BindingVD = BD->getHoldingVar())
12488 if (DeclMustBeEmitted(BindingVD))
12489 return true;
12490
12491 return false;
12492}
12493
12495 const FunctionDecl *FD,
12496 llvm::function_ref<void(FunctionDecl *)> Pred) const {
12497 assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
12498 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
12499 FD = FD->getMostRecentDecl();
12500 // FIXME: The order of traversal here matters and depends on the order of
12501 // lookup results, which happens to be (mostly) oldest-to-newest, but we
12502 // shouldn't rely on that.
12503 for (auto *CurDecl :
12505 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
12506 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
12507 !SeenDecls.contains(CurFD)) {
12508 SeenDecls.insert(CurFD);
12509 Pred(CurFD);
12510 }
12511 }
12512}
12513
12515 bool IsCXXMethod,
12516 bool IsBuiltin) const {
12517 // Pass through to the C++ ABI object
12518 if (IsCXXMethod)
12519 return ABI->getDefaultMethodCallConv(IsVariadic);
12520
12521 // Builtins ignore user-specified default calling convention and remain the
12522 // Target's default calling convention.
12523 if (!IsBuiltin) {
12524 switch (LangOpts.getDefaultCallingConv()) {
12526 break;
12528 return CC_C;
12530 if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
12531 return CC_X86FastCall;
12532 break;
12534 if (!IsVariadic)
12535 return CC_X86StdCall;
12536 break;
12538 // __vectorcall cannot be applied to variadic functions.
12539 if (!IsVariadic)
12540 return CC_X86VectorCall;
12541 break;
12543 // __regcall cannot be applied to variadic functions.
12544 if (!IsVariadic)
12545 return CC_X86RegCall;
12546 break;
12548 if (!IsVariadic)
12549 return CC_M68kRTD;
12550 break;
12551 }
12552 }
12553 return Target->getDefaultCallingConv();
12554}
12555
12557 // Pass through to the C++ ABI object
12558 return ABI->isNearlyEmpty(RD);
12559}
12560
12562 if (!VTContext.get()) {
12563 auto ABI = Target->getCXXABI();
12564 if (ABI.isMicrosoft())
12565 VTContext.reset(new MicrosoftVTableContext(*this));
12566 else {
12567 auto ComponentLayout = getLangOpts().RelativeCXXABIVTables
12570 VTContext.reset(new ItaniumVTableContext(*this, ComponentLayout));
12571 }
12572 }
12573 return VTContext.get();
12574}
12575
12577 if (!T)
12578 T = Target;
12579 switch (T->getCXXABI().getKind()) {
12580 case TargetCXXABI::AppleARM64:
12581 case TargetCXXABI::Fuchsia:
12582 case TargetCXXABI::GenericAArch64:
12583 case TargetCXXABI::GenericItanium:
12584 case TargetCXXABI::GenericARM:
12585 case TargetCXXABI::GenericMIPS:
12586 case TargetCXXABI::iOS:
12587 case TargetCXXABI::WebAssembly:
12588 case TargetCXXABI::WatchOS:
12589 case TargetCXXABI::XL:
12591 case TargetCXXABI::Microsoft:
12593 }
12594 llvm_unreachable("Unsupported ABI");
12595}
12596
12598 assert(T.getCXXABI().getKind() != TargetCXXABI::Microsoft &&
12599 "Device mangle context does not support Microsoft mangling.");
12600 switch (T.getCXXABI().getKind()) {
12601 case TargetCXXABI::AppleARM64:
12602 case TargetCXXABI::Fuchsia:
12603 case TargetCXXABI::GenericAArch64:
12604 case TargetCXXABI::GenericItanium:
12605 case TargetCXXABI::GenericARM:
12606 case TargetCXXABI::GenericMIPS:
12607 case TargetCXXABI::iOS:
12608 case TargetCXXABI::WebAssembly:
12609 case TargetCXXABI::WatchOS:
12610 case TargetCXXABI::XL:
12612 *this, getDiagnostics(),
12613 [](ASTContext &, const NamedDecl *ND) -> std::optional<unsigned> {
12614 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
12615 return RD->getDeviceLambdaManglingNumber();
12616 return std::nullopt;
12617 },
12618 /*IsAux=*/true);
12619 case TargetCXXABI::Microsoft:
12621 /*IsAux=*/true);
12622 }
12623 llvm_unreachable("Unsupported ABI");
12624}
12625
12626CXXABI::~CXXABI() = default;
12627
12629 return ASTRecordLayouts.getMemorySize() +
12630 llvm::capacity_in_bytes(ObjCLayouts) +
12631 llvm::capacity_in_bytes(KeyFunctions) +
12632 llvm::capacity_in_bytes(ObjCImpls) +
12633 llvm::capacity_in_bytes(BlockVarCopyInits) +
12634 llvm::capacity_in_bytes(DeclAttrs) +
12635 llvm::capacity_in_bytes(TemplateOrInstantiation) +
12636 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
12637 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
12638 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
12639 llvm::capacity_in_bytes(OverriddenMethods) +
12640 llvm::capacity_in_bytes(Types) +
12641 llvm::capacity_in_bytes(VariableArrayTypes);
12642}
12643
12644/// getIntTypeForBitwidth -
12645/// sets integer QualTy according to specified details:
12646/// bitwidth, signed/unsigned.
12647/// Returns empty type if there is no appropriate target types.
12649 unsigned Signed) const {
12651 CanQualType QualTy = getFromTargetType(Ty);
12652 if (!QualTy && DestWidth == 128)
12653 return Signed ? Int128Ty : UnsignedInt128Ty;
12654 return QualTy;
12655}
12656
12657/// getRealTypeForBitwidth -
12658/// sets floating point QualTy according to specified bitwidth.
12659/// Returns empty type if there is no appropriate target types.
12661 FloatModeKind ExplicitType) const {
12662 FloatModeKind Ty =
12663 getTargetInfo().getRealTypeByWidth(DestWidth, ExplicitType);
12664 switch (Ty) {
12666 return HalfTy;
12668 return FloatTy;
12670 return DoubleTy;
12672 return LongDoubleTy;
12674 return Float128Ty;
12676 return Ibm128Ty;
12678 return {};
12679 }
12680
12681 llvm_unreachable("Unhandled TargetInfo::RealType value");
12682}
12683
12684void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
12685 if (Number <= 1)
12686 return;
12687
12688 MangleNumbers[ND] = Number;
12689
12690 if (Listener)
12691 Listener->AddedManglingNumber(ND, Number);
12692}
12693
12695 bool ForAuxTarget) const {
12696 auto I = MangleNumbers.find(ND);
12697 unsigned Res = I != MangleNumbers.end() ? I->second : 1;
12698 // CUDA/HIP host compilation encodes host and device mangling numbers
12699 // as lower and upper half of 32 bit integer.
12700 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice) {
12701 Res = ForAuxTarget ? Res >> 16 : Res & 0xFFFF;
12702 } else {
12703 assert(!ForAuxTarget && "Only CUDA/HIP host compilation supports mangling "
12704 "number for aux target");
12705 }
12706 return Res > 1 ? Res : 1;
12707}
12708
12709void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
12710 if (Number <= 1)
12711 return;
12712
12713 StaticLocalNumbers[VD] = Number;
12714
12715 if (Listener)
12716 Listener->AddedStaticLocalNumbers(VD, Number);
12717}
12718
12720 auto I = StaticLocalNumbers.find(VD);
12721 return I != StaticLocalNumbers.end() ? I->second : 1;
12722}
12723
12726 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
12727 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
12728 if (!MCtx)
12730 return *MCtx;
12731}
12732
12735 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
12736 std::unique_ptr<MangleNumberingContext> &MCtx =
12737 ExtraMangleNumberingContexts[D];
12738 if (!MCtx)
12740 return *MCtx;
12741}
12742
12743std::unique_ptr<MangleNumberingContext>
12745 return ABI->createMangleNumberingContext();
12746}
12747
12748const CXXConstructorDecl *
12750 return ABI->getCopyConstructorForExceptionObject(
12751 cast<CXXRecordDecl>(RD->getFirstDecl()));
12752}
12753
12755 CXXConstructorDecl *CD) {
12756 return ABI->addCopyConstructorForExceptionObject(
12757 cast<CXXRecordDecl>(RD->getFirstDecl()),
12758 cast<CXXConstructorDecl>(CD->getFirstDecl()));
12759}
12760
12762 TypedefNameDecl *DD) {
12763 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
12764}
12765
12768 return ABI->getTypedefNameForUnnamedTagDecl(TD);
12769}
12770
12772 DeclaratorDecl *DD) {
12773 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
12774}
12775
12777 return ABI->getDeclaratorForUnnamedTagDecl(TD);
12778}
12779
12780void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
12781 ParamIndices[D] = index;
12782}
12783
12785 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
12786 assert(I != ParamIndices.end() &&
12787 "ParmIndices lacks entry set by ParmVarDecl");
12788 return I->second;
12789}
12790
12792 unsigned Length) const {
12793 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
12794 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
12795 EltTy = EltTy.withConst();
12796
12797 EltTy = adjustStringLiteralBaseType(EltTy);
12798
12799 // Get an array type for the string, according to C99 6.4.5. This includes
12800 // the null terminator character.
12801 return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr,
12802 ArraySizeModifier::Normal, /*IndexTypeQuals*/ 0);
12803}
12804
12807 StringLiteral *&Result = StringLiteralCache[Key];
12808 if (!Result)
12810 *this, Key, StringLiteralKind::Ordinary,
12811 /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()),
12812 SourceLocation());
12813 return Result;
12814}
12815
12816MSGuidDecl *
12818 assert(MSGuidTagDecl && "building MS GUID without MS extensions?");
12819
12820 llvm::FoldingSetNodeID ID;
12821 MSGuidDecl::Profile(ID, Parts);
12822
12823 void *InsertPos;
12824 if (MSGuidDecl *Existing = MSGuidDecls.FindNodeOrInsertPos(ID, InsertPos))
12825 return Existing;
12826
12827 QualType GUIDType = getMSGuidType().withConst();
12828 MSGuidDecl *New = MSGuidDecl::Create(*this, GUIDType, Parts);
12829 MSGuidDecls.InsertNode(New, InsertPos);
12830 return New;
12831}
12832
12835 const APValue &APVal) const {
12836 llvm::FoldingSetNodeID ID;
12838
12839 void *InsertPos;
12840 if (UnnamedGlobalConstantDecl *Existing =
12841 UnnamedGlobalConstantDecls.FindNodeOrInsertPos(ID, InsertPos))
12842 return Existing;
12843
12845 UnnamedGlobalConstantDecl::Create(*this, Ty, APVal);
12846 UnnamedGlobalConstantDecls.InsertNode(New, InsertPos);
12847 return New;
12848}
12849
12852 assert(T->isRecordType() && "template param object of unexpected type");
12853
12854 // C++ [temp.param]p8:
12855 // [...] a static storage duration object of type 'const T' [...]
12856 T.addConst();
12857
12858 llvm::FoldingSetNodeID ID;
12860
12861 void *InsertPos;
12862 if (TemplateParamObjectDecl *Existing =
12863 TemplateParamObjectDecls.FindNodeOrInsertPos(ID, InsertPos))
12864 return Existing;
12865
12866 TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(*this, T, V);
12867 TemplateParamObjectDecls.InsertNode(New, InsertPos);
12868 return New;
12869}
12870
12872 const llvm::Triple &T = getTargetInfo().getTriple();
12873 if (!T.isOSDarwin())
12874 return false;
12875
12876 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
12877 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
12878 return false;
12879
12880 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
12881 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
12882 uint64_t Size = sizeChars.getQuantity();
12883 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
12884 unsigned Align = alignChars.getQuantity();
12885 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
12886 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
12887}
12888
12889bool
12891 const ObjCMethodDecl *MethodImpl) {
12892 // No point trying to match an unavailable/deprecated mothod.
12893 if (MethodDecl->hasAttr<UnavailableAttr>()
12894 || MethodDecl->hasAttr<DeprecatedAttr>())
12895 return false;
12896 if (MethodDecl->getObjCDeclQualifier() !=
12897 MethodImpl->getObjCDeclQualifier())
12898 return false;
12899 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
12900 return false;
12901
12902 if (MethodDecl->param_size() != MethodImpl->param_size())
12903 return false;
12904
12905 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
12906 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
12907 EF = MethodDecl->param_end();
12908 IM != EM && IF != EF; ++IM, ++IF) {
12909 const ParmVarDecl *DeclVar = (*IF);
12910 const ParmVarDecl *ImplVar = (*IM);
12911 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
12912 return false;
12913 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
12914 return false;
12915 }
12916
12917 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
12918}
12919
12921 LangAS AS;
12923 AS = LangAS::Default;
12924 else
12925 AS = QT->getPointeeType().getAddressSpace();
12926
12928}
12929
12932}
12933
12934bool ASTContext::hasSameExpr(const Expr *X, const Expr *Y) const {
12935 if (X == Y)
12936 return true;
12937 if (!X || !Y)
12938 return false;
12939 llvm::FoldingSetNodeID IDX, IDY;
12940 X->Profile(IDX, *this, /*Canonical=*/true);
12941 Y->Profile(IDY, *this, /*Canonical=*/true);
12942 return IDX == IDY;
12943}
12944
12945// The getCommon* helpers return, for given 'same' X and Y entities given as
12946// inputs, another entity which is also the 'same' as the inputs, but which
12947// is closer to the canonical form of the inputs, each according to a given
12948// criteria.
12949// The getCommon*Checked variants are 'null inputs not-allowed' equivalents of
12950// the regular ones.
12951
12953 if (!declaresSameEntity(X, Y))
12954 return nullptr;
12955 for (const Decl *DX : X->redecls()) {
12956 // If we reach Y before reaching the first decl, that means X is older.
12957 if (DX == Y)
12958 return X;
12959 // If we reach the first decl, then Y is older.
12960 if (DX->isFirstDecl())
12961 return Y;
12962 }
12963 llvm_unreachable("Corrupt redecls chain");
12964}
12965
12966template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
12967static T *getCommonDecl(T *X, T *Y) {
12968 return cast_or_null<T>(
12969 getCommonDecl(const_cast<Decl *>(cast_or_null<Decl>(X)),
12970 const_cast<Decl *>(cast_or_null<Decl>(Y))));
12971}
12972
12973template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
12974static T *getCommonDeclChecked(T *X, T *Y) {
12975 return cast<T>(getCommonDecl(const_cast<Decl *>(cast<Decl>(X)),
12976 const_cast<Decl *>(cast<Decl>(Y))));
12977}
12978
12980 TemplateName Y) {
12981 if (X.getAsVoidPointer() == Y.getAsVoidPointer())
12982 return X;
12983 // FIXME: There are cases here where we could find a common template name
12984 // with more sugar. For example one could be a SubstTemplateTemplate*
12985 // replacing the other.
12987 if (CX.getAsVoidPointer() !=
12989 return TemplateName();
12990 return CX;
12991}
12992
12993static TemplateName
12996 assert(R.getAsVoidPointer() != nullptr);
12997 return R;
12998}
12999
13001 ArrayRef<QualType> Ys, bool Unqualified = false) {
13002 assert(Xs.size() == Ys.size());
13003 SmallVector<QualType, 8> Rs(Xs.size());
13004 for (size_t I = 0; I < Rs.size(); ++I)
13005 Rs[I] = Ctx.getCommonSugaredType(Xs[I], Ys[I], Unqualified);
13006 return Rs;
13007}
13008
13009template <class T>
13010static SourceLocation getCommonAttrLoc(const T *X, const T *Y) {
13011 return X->getAttributeLoc() == Y->getAttributeLoc() ? X->getAttributeLoc()
13012 : SourceLocation();
13013}
13014
13016 const TemplateArgument &X,
13017 const TemplateArgument &Y) {
13018 if (X.getKind() != Y.getKind())
13019 return TemplateArgument();
13020
13021 switch (X.getKind()) {
13023 if (!Ctx.hasSameType(X.getAsType(), Y.getAsType()))
13024 return TemplateArgument();
13025 return TemplateArgument(
13026 Ctx.getCommonSugaredType(X.getAsType(), Y.getAsType()));
13028 if (!Ctx.hasSameType(X.getNullPtrType(), Y.getNullPtrType()))
13029 return TemplateArgument();
13030 return TemplateArgument(
13031 Ctx.getCommonSugaredType(X.getNullPtrType(), Y.getNullPtrType()),
13032 /*Unqualified=*/true);
13034 if (!Ctx.hasSameType(X.getAsExpr()->getType(), Y.getAsExpr()->getType()))
13035 return TemplateArgument();
13036 // FIXME: Try to keep the common sugar.
13037 return X;
13039 TemplateName TX = X.getAsTemplate(), TY = Y.getAsTemplate();
13040 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
13041 if (!CTN.getAsVoidPointer())
13042 return TemplateArgument();
13043 return TemplateArgument(CTN);
13044 }
13046 TemplateName TX = X.getAsTemplateOrTemplatePattern(),
13048 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
13049 if (!CTN.getAsVoidPointer())
13050 return TemplateName();
13051 auto NExpX = X.getNumTemplateExpansions();
13052 assert(NExpX == Y.getNumTemplateExpansions());
13053 return TemplateArgument(CTN, NExpX);
13054 }
13055 default:
13056 // FIXME: Handle the other argument kinds.
13057 return X;
13058 }
13059}
13060
13065 if (Xs.size() != Ys.size())
13066 return true;
13067 R.resize(Xs.size());
13068 for (size_t I = 0; I < R.size(); ++I) {
13069 R[I] = getCommonTemplateArgument(Ctx, Xs[I], Ys[I]);
13070 if (R[I].isNull())
13071 return true;
13072 }
13073 return false;
13074}
13075
13080 bool Different = getCommonTemplateArguments(Ctx, R, Xs, Ys);
13081 assert(!Different);
13082 (void)Different;
13083 return R;
13084}
13085
13086template <class T>
13088 return X->getKeyword() == Y->getKeyword() ? X->getKeyword()
13090}
13091
13092template <class T>
13094 const T *Y) {
13095 // FIXME: Try to keep the common NNS sugar.
13096 return X->getQualifier() == Y->getQualifier()
13097 ? X->getQualifier()
13098 : Ctx.getCanonicalNestedNameSpecifier(X->getQualifier());
13099}
13100
13101template <class T>
13102static QualType getCommonElementType(ASTContext &Ctx, const T *X, const T *Y) {
13103 return Ctx.getCommonSugaredType(X->getElementType(), Y->getElementType());
13104}
13105
13106template <class T>
13108 Qualifiers &QX, const T *Y,
13109 Qualifiers &QY) {
13110 QualType EX = X->getElementType(), EY = Y->getElementType();
13111 QualType R = Ctx.getCommonSugaredType(EX, EY,
13112 /*Unqualified=*/true);
13113 Qualifiers RQ = R.getQualifiers();
13114 QX += EX.getQualifiers() - RQ;
13115 QY += EY.getQualifiers() - RQ;
13116 return R;
13117}
13118
13119template <class T>
13120static QualType getCommonPointeeType(ASTContext &Ctx, const T *X, const T *Y) {
13121 return Ctx.getCommonSugaredType(X->getPointeeType(), Y->getPointeeType());
13122}
13123
13124template <class T> static auto *getCommonSizeExpr(ASTContext &Ctx, T *X, T *Y) {
13125 assert(Ctx.hasSameExpr(X->getSizeExpr(), Y->getSizeExpr()));
13126 return X->getSizeExpr();
13127}
13128
13129static auto getCommonSizeModifier(const ArrayType *X, const ArrayType *Y) {
13130 assert(X->getSizeModifier() == Y->getSizeModifier());
13131 return X->getSizeModifier();
13132}
13133
13135 const ArrayType *Y) {
13136 assert(X->getIndexTypeCVRQualifiers() == Y->getIndexTypeCVRQualifiers());
13137 return X->getIndexTypeCVRQualifiers();
13138}
13139
13140// Merges two type lists such that the resulting vector will contain
13141// each type (in a canonical sense) only once, in the order they appear
13142// from X to Y. If they occur in both X and Y, the result will contain
13143// the common sugared type between them.
13146 llvm::DenseMap<QualType, unsigned> Found;
13147 for (auto Ts : {X, Y}) {
13148 for (QualType T : Ts) {
13149 auto Res = Found.try_emplace(Ctx.getCanonicalType(T), Out.size());
13150 if (!Res.second) {
13151 QualType &U = Out[Res.first->second];
13152 U = Ctx.getCommonSugaredType(U, T);
13153 } else {
13154 Out.emplace_back(T);
13155 }
13156 }
13157 }
13158}
13159
13163 SmallVectorImpl<QualType> &ExceptionTypeStorage,
13164 bool AcceptDependent) {
13165 ExceptionSpecificationType EST1 = ESI1.Type, EST2 = ESI2.Type;
13166
13167 // If either of them can throw anything, that is the result.
13168 for (auto I : {EST_None, EST_MSAny, EST_NoexceptFalse}) {
13169 if (EST1 == I)
13170 return ESI1;
13171 if (EST2 == I)
13172 return ESI2;
13173 }
13174
13175 // If either of them is non-throwing, the result is the other.
13176 for (auto I :
13178 if (EST1 == I)
13179 return ESI2;
13180 if (EST2 == I)
13181 return ESI1;
13182 }
13183
13184 // If we're left with value-dependent computed noexcept expressions, we're
13185 // stuck. Before C++17, we can just drop the exception specification entirely,
13186 // since it's not actually part of the canonical type. And this should never
13187 // happen in C++17, because it would mean we were computing the composite
13188 // pointer type of dependent types, which should never happen.
13189 if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) {
13190 assert(AcceptDependent &&
13191 "computing composite pointer type of dependent types");
13193 }
13194
13195 // Switch over the possibilities so that people adding new values know to
13196 // update this function.
13197 switch (EST1) {
13198 case EST_None:
13199 case EST_DynamicNone:
13200 case EST_MSAny:
13201 case EST_BasicNoexcept:
13203 case EST_NoexceptFalse:
13204 case EST_NoexceptTrue:
13205 case EST_NoThrow:
13206 llvm_unreachable("These ESTs should be handled above");
13207
13208 case EST_Dynamic: {
13209 // This is the fun case: both exception specifications are dynamic. Form
13210 // the union of the two lists.
13211 assert(EST2 == EST_Dynamic && "other cases should already be handled");
13212 mergeTypeLists(*this, ExceptionTypeStorage, ESI1.Exceptions,
13213 ESI2.Exceptions);
13215 Result.Exceptions = ExceptionTypeStorage;
13216 return Result;
13217 }
13218
13219 case EST_Unevaluated:
13220 case EST_Uninstantiated:
13221 case EST_Unparsed:
13222 llvm_unreachable("shouldn't see unresolved exception specifications here");
13223 }
13224
13225 llvm_unreachable("invalid ExceptionSpecificationType");
13226}
13227
13229 Qualifiers &QX, const Type *Y,
13230 Qualifiers &QY) {
13231 Type::TypeClass TC = X->getTypeClass();
13232 assert(TC == Y->getTypeClass());
13233 switch (TC) {
13234#define UNEXPECTED_TYPE(Class, Kind) \
13235 case Type::Class: \
13236 llvm_unreachable("Unexpected " Kind ": " #Class);
13237
13238#define NON_CANONICAL_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "non-canonical")
13239#define TYPE(Class, Base)
13240#include "clang/AST/TypeNodes.inc"
13241
13242#define SUGAR_FREE_TYPE(Class) UNEXPECTED_TYPE(Class, "sugar-free")
13243 SUGAR_FREE_TYPE(Builtin)
13244 SUGAR_FREE_TYPE(DeducedTemplateSpecialization)
13245 SUGAR_FREE_TYPE(DependentBitInt)
13248 SUGAR_FREE_TYPE(ObjCInterface)
13250 SUGAR_FREE_TYPE(SubstTemplateTypeParmPack)
13251 SUGAR_FREE_TYPE(UnresolvedUsing)
13252#undef SUGAR_FREE_TYPE
13253#define NON_UNIQUE_TYPE(Class) UNEXPECTED_TYPE(Class, "non-unique")
13254 NON_UNIQUE_TYPE(TypeOfExpr)
13255 NON_UNIQUE_TYPE(VariableArray)
13256#undef NON_UNIQUE_TYPE
13257
13258 UNEXPECTED_TYPE(TypeOf, "sugar")
13259
13260#undef UNEXPECTED_TYPE
13261
13262 case Type::Auto: {
13263 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
13264 assert(AX->getDeducedType().isNull());
13265 assert(AY->getDeducedType().isNull());
13266 assert(AX->getKeyword() == AY->getKeyword());
13267 assert(AX->isInstantiationDependentType() ==
13268 AY->isInstantiationDependentType());
13269 auto As = getCommonTemplateArguments(Ctx, AX->getTypeConstraintArguments(),
13270 AY->getTypeConstraintArguments());
13271 return Ctx.getAutoType(QualType(), AX->getKeyword(),
13273 AX->containsUnexpandedParameterPack(),
13274 getCommonDeclChecked(AX->getTypeConstraintConcept(),
13275 AY->getTypeConstraintConcept()),
13276 As);
13277 }
13278 case Type::IncompleteArray: {
13279 const auto *AX = cast<IncompleteArrayType>(X),
13280 *AY = cast<IncompleteArrayType>(Y);
13281 return Ctx.getIncompleteArrayType(
13282 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
13284 }
13285 case Type::DependentSizedArray: {
13286 const auto *AX = cast<DependentSizedArrayType>(X),
13287 *AY = cast<DependentSizedArrayType>(Y);
13288 return Ctx.getDependentSizedArrayType(
13289 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
13290 getCommonSizeExpr(Ctx, AX, AY), getCommonSizeModifier(AX, AY),
13292 AX->getBracketsRange() == AY->getBracketsRange()
13293 ? AX->getBracketsRange()
13294 : SourceRange());
13295 }
13296 case Type::ConstantArray: {
13297 const auto *AX = cast<ConstantArrayType>(X),
13298 *AY = cast<ConstantArrayType>(Y);
13299 assert(AX->getSize() == AY->getSize());
13300 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
13301 ? AX->getSizeExpr()
13302 : nullptr;
13303 return Ctx.getConstantArrayType(
13304 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
13306 }
13307 case Type::ArrayParameter: {
13308 const auto *AX = cast<ArrayParameterType>(X),
13309 *AY = cast<ArrayParameterType>(Y);
13310 assert(AX->getSize() == AY->getSize());
13311 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
13312 ? AX->getSizeExpr()
13313 : nullptr;
13314 auto ArrayTy = Ctx.getConstantArrayType(
13315 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
13317 return Ctx.getArrayParameterType(ArrayTy);
13318 }
13319 case Type::Atomic: {
13320 const auto *AX = cast<AtomicType>(X), *AY = cast<AtomicType>(Y);
13321 return Ctx.getAtomicType(
13322 Ctx.getCommonSugaredType(AX->getValueType(), AY->getValueType()));
13323 }
13324 case Type::Complex: {
13325 const auto *CX = cast<ComplexType>(X), *CY = cast<ComplexType>(Y);
13326 return Ctx.getComplexType(getCommonArrayElementType(Ctx, CX, QX, CY, QY));
13327 }
13328 case Type::Pointer: {
13329 const auto *PX = cast<PointerType>(X), *PY = cast<PointerType>(Y);
13330 return Ctx.getPointerType(getCommonPointeeType(Ctx, PX, PY));
13331 }
13332 case Type::BlockPointer: {
13333 const auto *PX = cast<BlockPointerType>(X), *PY = cast<BlockPointerType>(Y);
13334 return Ctx.getBlockPointerType(getCommonPointeeType(Ctx, PX, PY));
13335 }
13336 case Type::ObjCObjectPointer: {
13337 const auto *PX = cast<ObjCObjectPointerType>(X),
13338 *PY = cast<ObjCObjectPointerType>(Y);
13339 return Ctx.getObjCObjectPointerType(getCommonPointeeType(Ctx, PX, PY));
13340 }
13341 case Type::MemberPointer: {
13342 const auto *PX = cast<MemberPointerType>(X),
13343 *PY = cast<MemberPointerType>(Y);
13344 return Ctx.getMemberPointerType(
13345 getCommonPointeeType(Ctx, PX, PY),
13346 Ctx.getCommonSugaredType(QualType(PX->getClass(), 0),
13347 QualType(PY->getClass(), 0))
13348 .getTypePtr());
13349 }
13350 case Type::LValueReference: {
13351 const auto *PX = cast<LValueReferenceType>(X),
13352 *PY = cast<LValueReferenceType>(Y);
13353 // FIXME: Preserve PointeeTypeAsWritten.
13354 return Ctx.getLValueReferenceType(getCommonPointeeType(Ctx, PX, PY),
13355 PX->isSpelledAsLValue() ||
13356 PY->isSpelledAsLValue());
13357 }
13358 case Type::RValueReference: {
13359 const auto *PX = cast<RValueReferenceType>(X),
13360 *PY = cast<RValueReferenceType>(Y);
13361 // FIXME: Preserve PointeeTypeAsWritten.
13362 return Ctx.getRValueReferenceType(getCommonPointeeType(Ctx, PX, PY));
13363 }
13364 case Type::DependentAddressSpace: {
13365 const auto *PX = cast<DependentAddressSpaceType>(X),
13366 *PY = cast<DependentAddressSpaceType>(Y);
13367 assert(Ctx.hasSameExpr(PX->getAddrSpaceExpr(), PY->getAddrSpaceExpr()));
13368 return Ctx.getDependentAddressSpaceType(getCommonPointeeType(Ctx, PX, PY),
13369 PX->getAddrSpaceExpr(),
13370 getCommonAttrLoc(PX, PY));
13371 }
13372 case Type::FunctionNoProto: {
13373 const auto *FX = cast<FunctionNoProtoType>(X),
13374 *FY = cast<FunctionNoProtoType>(Y);
13375 assert(FX->getExtInfo() == FY->getExtInfo());
13376 return Ctx.getFunctionNoProtoType(
13377 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType()),
13378 FX->getExtInfo());
13379 }
13380 case Type::FunctionProto: {
13381 const auto *FX = cast<FunctionProtoType>(X),
13382 *FY = cast<FunctionProtoType>(Y);
13383 FunctionProtoType::ExtProtoInfo EPIX = FX->getExtProtoInfo(),
13384 EPIY = FY->getExtProtoInfo();
13385 assert(EPIX.ExtInfo == EPIY.ExtInfo);
13386 assert(EPIX.ExtParameterInfos == EPIY.ExtParameterInfos);
13387 assert(EPIX.RefQualifier == EPIY.RefQualifier);
13388 assert(EPIX.TypeQuals == EPIY.TypeQuals);
13389 assert(EPIX.Variadic == EPIY.Variadic);
13390
13391 // FIXME: Can we handle an empty EllipsisLoc?
13392 // Use emtpy EllipsisLoc if X and Y differ.
13393
13394 EPIX.HasTrailingReturn = EPIX.HasTrailingReturn && EPIY.HasTrailingReturn;
13395
13396 QualType R =
13397 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType());
13398 auto P = getCommonTypes(Ctx, FX->param_types(), FY->param_types(),
13399 /*Unqualified=*/true);
13400
13401 SmallVector<QualType, 8> Exceptions;
13403 EPIX.ExceptionSpec, EPIY.ExceptionSpec, Exceptions, true);
13404 return Ctx.getFunctionType(R, P, EPIX);
13405 }
13406 case Type::ObjCObject: {
13407 const auto *OX = cast<ObjCObjectType>(X), *OY = cast<ObjCObjectType>(Y);
13408 assert(
13409 std::equal(OX->getProtocols().begin(), OX->getProtocols().end(),
13410 OY->getProtocols().begin(), OY->getProtocols().end(),
13411 [](const ObjCProtocolDecl *P0, const ObjCProtocolDecl *P1) {
13412 return P0->getCanonicalDecl() == P1->getCanonicalDecl();
13413 }) &&
13414 "protocol lists must be the same");
13415 auto TAs = getCommonTypes(Ctx, OX->getTypeArgsAsWritten(),
13416 OY->getTypeArgsAsWritten());
13417 return Ctx.getObjCObjectType(
13418 Ctx.getCommonSugaredType(OX->getBaseType(), OY->getBaseType()), TAs,
13419 OX->getProtocols(),
13420 OX->isKindOfTypeAsWritten() && OY->isKindOfTypeAsWritten());
13421 }
13422 case Type::ConstantMatrix: {
13423 const auto *MX = cast<ConstantMatrixType>(X),
13424 *MY = cast<ConstantMatrixType>(Y);
13425 assert(MX->getNumRows() == MY->getNumRows());
13426 assert(MX->getNumColumns() == MY->getNumColumns());
13427 return Ctx.getConstantMatrixType(getCommonElementType(Ctx, MX, MY),
13428 MX->getNumRows(), MX->getNumColumns());
13429 }
13430 case Type::DependentSizedMatrix: {
13431 const auto *MX = cast<DependentSizedMatrixType>(X),
13432 *MY = cast<DependentSizedMatrixType>(Y);
13433 assert(Ctx.hasSameExpr(MX->getRowExpr(), MY->getRowExpr()));
13434 assert(Ctx.hasSameExpr(MX->getColumnExpr(), MY->getColumnExpr()));
13435 return Ctx.getDependentSizedMatrixType(
13436 getCommonElementType(Ctx, MX, MY), MX->getRowExpr(),
13437 MX->getColumnExpr(), getCommonAttrLoc(MX, MY));
13438 }
13439 case Type::Vector: {
13440 const auto *VX = cast<VectorType>(X), *VY = cast<VectorType>(Y);
13441 assert(VX->getNumElements() == VY->getNumElements());
13442 assert(VX->getVectorKind() == VY->getVectorKind());
13443 return Ctx.getVectorType(getCommonElementType(Ctx, VX, VY),
13444 VX->getNumElements(), VX->getVectorKind());
13445 }
13446 case Type::ExtVector: {
13447 const auto *VX = cast<ExtVectorType>(X), *VY = cast<ExtVectorType>(Y);
13448 assert(VX->getNumElements() == VY->getNumElements());
13449 return Ctx.getExtVectorType(getCommonElementType(Ctx, VX, VY),
13450 VX->getNumElements());
13451 }
13452 case Type::DependentSizedExtVector: {
13453 const auto *VX = cast<DependentSizedExtVectorType>(X),
13454 *VY = cast<DependentSizedExtVectorType>(Y);
13456 getCommonSizeExpr(Ctx, VX, VY),
13457 getCommonAttrLoc(VX, VY));
13458 }
13459 case Type::DependentVector: {
13460 const auto *VX = cast<DependentVectorType>(X),
13461 *VY = cast<DependentVectorType>(Y);
13462 assert(VX->getVectorKind() == VY->getVectorKind());
13463 return Ctx.getDependentVectorType(
13464 getCommonElementType(Ctx, VX, VY), getCommonSizeExpr(Ctx, VX, VY),
13465 getCommonAttrLoc(VX, VY), VX->getVectorKind());
13466 }
13467 case Type::InjectedClassName: {
13468 const auto *IX = cast<InjectedClassNameType>(X),
13469 *IY = cast<InjectedClassNameType>(Y);
13470 return Ctx.getInjectedClassNameType(
13471 getCommonDeclChecked(IX->getDecl(), IY->getDecl()),
13472 Ctx.getCommonSugaredType(IX->getInjectedSpecializationType(),
13473 IY->getInjectedSpecializationType()));
13474 }
13475 case Type::TemplateSpecialization: {
13476 const auto *TX = cast<TemplateSpecializationType>(X),
13477 *TY = cast<TemplateSpecializationType>(Y);
13478 auto As = getCommonTemplateArguments(Ctx, TX->template_arguments(),
13479 TY->template_arguments());
13481 ::getCommonTemplateNameChecked(Ctx, TX->getTemplateName(),
13482 TY->getTemplateName()),
13483 As, X->getCanonicalTypeInternal());
13484 }
13485 case Type::Decltype: {
13486 const auto *DX = cast<DecltypeType>(X);
13487 [[maybe_unused]] const auto *DY = cast<DecltypeType>(Y);
13488 assert(DX->isDependentType());
13489 assert(DY->isDependentType());
13490 assert(Ctx.hasSameExpr(DX->getUnderlyingExpr(), DY->getUnderlyingExpr()));
13491 // As Decltype is not uniqued, building a common type would be wasteful.
13492 return QualType(DX, 0);
13493 }
13494 case Type::PackIndexing: {
13495 const auto *DX = cast<PackIndexingType>(X);
13496 [[maybe_unused]] const auto *DY = cast<PackIndexingType>(Y);
13497 assert(DX->isDependentType());
13498 assert(DY->isDependentType());
13499 assert(Ctx.hasSameExpr(DX->getIndexExpr(), DY->getIndexExpr()));
13500 return QualType(DX, 0);
13501 }
13502 case Type::DependentName: {
13503 const auto *NX = cast<DependentNameType>(X),
13504 *NY = cast<DependentNameType>(Y);
13505 assert(NX->getIdentifier() == NY->getIdentifier());
13506 return Ctx.getDependentNameType(
13507 getCommonTypeKeyword(NX, NY), getCommonNNS(Ctx, NX, NY),
13508 NX->getIdentifier(), NX->getCanonicalTypeInternal());
13509 }
13510 case Type::DependentTemplateSpecialization: {
13511 const auto *TX = cast<DependentTemplateSpecializationType>(X),
13512 *TY = cast<DependentTemplateSpecializationType>(Y);
13513 assert(TX->getIdentifier() == TY->getIdentifier());
13514 auto As = getCommonTemplateArguments(Ctx, TX->template_arguments(),
13515 TY->template_arguments());
13517 getCommonTypeKeyword(TX, TY), getCommonNNS(Ctx, TX, TY),
13518 TX->getIdentifier(), As);
13519 }
13520 case Type::UnaryTransform: {
13521 const auto *TX = cast<UnaryTransformType>(X),
13522 *TY = cast<UnaryTransformType>(Y);
13523 assert(TX->getUTTKind() == TY->getUTTKind());
13524 return Ctx.getUnaryTransformType(
13525 Ctx.getCommonSugaredType(TX->getBaseType(), TY->getBaseType()),
13526 Ctx.getCommonSugaredType(TX->getUnderlyingType(),
13527 TY->getUnderlyingType()),
13528 TX->getUTTKind());
13529 }
13530 case Type::PackExpansion: {
13531 const auto *PX = cast<PackExpansionType>(X),
13532 *PY = cast<PackExpansionType>(Y);
13533 assert(PX->getNumExpansions() == PY->getNumExpansions());
13534 return Ctx.getPackExpansionType(
13535 Ctx.getCommonSugaredType(PX->getPattern(), PY->getPattern()),
13536 PX->getNumExpansions(), false);
13537 }
13538 case Type::Pipe: {
13539 const auto *PX = cast<PipeType>(X), *PY = cast<PipeType>(Y);
13540 assert(PX->isReadOnly() == PY->isReadOnly());
13541 auto MP = PX->isReadOnly() ? &ASTContext::getReadPipeType
13543 return (Ctx.*MP)(getCommonElementType(Ctx, PX, PY));
13544 }
13545 case Type::TemplateTypeParm: {
13546 const auto *TX = cast<TemplateTypeParmType>(X),
13547 *TY = cast<TemplateTypeParmType>(Y);
13548 assert(TX->getDepth() == TY->getDepth());
13549 assert(TX->getIndex() == TY->getIndex());
13550 assert(TX->isParameterPack() == TY->isParameterPack());
13551 return Ctx.getTemplateTypeParmType(
13552 TX->getDepth(), TX->getIndex(), TX->isParameterPack(),
13553 getCommonDecl(TX->getDecl(), TY->getDecl()));
13554 }
13555 }
13556 llvm_unreachable("Unknown Type Class");
13557}
13558
13560 const Type *Y,
13561 SplitQualType Underlying) {
13562 Type::TypeClass TC = X->getTypeClass();
13563 if (TC != Y->getTypeClass())
13564 return QualType();
13565 switch (TC) {
13566#define UNEXPECTED_TYPE(Class, Kind) \
13567 case Type::Class: \
13568 llvm_unreachable("Unexpected " Kind ": " #Class);
13569#define TYPE(Class, Base)
13570#define DEPENDENT_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "dependent")
13571#include "clang/AST/TypeNodes.inc"
13572
13573#define CANONICAL_TYPE(Class) UNEXPECTED_TYPE(Class, "canonical")
13576 CANONICAL_TYPE(BlockPointer)
13577 CANONICAL_TYPE(Builtin)
13579 CANONICAL_TYPE(ConstantArray)
13580 CANONICAL_TYPE(ArrayParameter)
13581 CANONICAL_TYPE(ConstantMatrix)
13583 CANONICAL_TYPE(ExtVector)
13584 CANONICAL_TYPE(FunctionNoProto)
13585 CANONICAL_TYPE(FunctionProto)
13586 CANONICAL_TYPE(IncompleteArray)
13587 CANONICAL_TYPE(LValueReference)
13588 CANONICAL_TYPE(MemberPointer)
13589 CANONICAL_TYPE(ObjCInterface)
13590 CANONICAL_TYPE(ObjCObject)
13591 CANONICAL_TYPE(ObjCObjectPointer)
13595 CANONICAL_TYPE(RValueReference)
13596 CANONICAL_TYPE(VariableArray)
13598#undef CANONICAL_TYPE
13599
13600#undef UNEXPECTED_TYPE
13601
13602 case Type::Adjusted: {
13603 const auto *AX = cast<AdjustedType>(X), *AY = cast<AdjustedType>(Y);
13604 QualType OX = AX->getOriginalType(), OY = AY->getOriginalType();
13605 if (!Ctx.hasSameType(OX, OY))
13606 return QualType();
13607 // FIXME: It's inefficient to have to unify the original types.
13608 return Ctx.getAdjustedType(Ctx.getCommonSugaredType(OX, OY),
13609 Ctx.getQualifiedType(Underlying));
13610 }
13611 case Type::Decayed: {
13612 const auto *DX = cast<DecayedType>(X), *DY = cast<DecayedType>(Y);
13613 QualType OX = DX->getOriginalType(), OY = DY->getOriginalType();
13614 if (!Ctx.hasSameType(OX, OY))
13615 return QualType();
13616 // FIXME: It's inefficient to have to unify the original types.
13617 return Ctx.getDecayedType(Ctx.getCommonSugaredType(OX, OY),
13618 Ctx.getQualifiedType(Underlying));
13619 }
13620 case Type::Attributed: {
13621 const auto *AX = cast<AttributedType>(X), *AY = cast<AttributedType>(Y);
13622 AttributedType::Kind Kind = AX->getAttrKind();
13623 if (Kind != AY->getAttrKind())
13624 return QualType();
13625 QualType MX = AX->getModifiedType(), MY = AY->getModifiedType();
13626 if (!Ctx.hasSameType(MX, MY))
13627 return QualType();
13628 // FIXME: It's inefficient to have to unify the modified types.
13629 return Ctx.getAttributedType(Kind, Ctx.getCommonSugaredType(MX, MY),
13630 Ctx.getQualifiedType(Underlying));
13631 }
13632 case Type::BTFTagAttributed: {
13633 const auto *BX = cast<BTFTagAttributedType>(X);
13634 const BTFTypeTagAttr *AX = BX->getAttr();
13635 // The attribute is not uniqued, so just compare the tag.
13636 if (AX->getBTFTypeTag() !=
13637 cast<BTFTagAttributedType>(Y)->getAttr()->getBTFTypeTag())
13638 return QualType();
13639 return Ctx.getBTFTagAttributedType(AX, Ctx.getQualifiedType(Underlying));
13640 }
13641 case Type::Auto: {
13642 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
13643
13644 AutoTypeKeyword KW = AX->getKeyword();
13645 if (KW != AY->getKeyword())
13646 return QualType();
13647
13648 ConceptDecl *CD = ::getCommonDecl(AX->getTypeConstraintConcept(),
13649 AY->getTypeConstraintConcept());
13651 if (CD &&
13652 getCommonTemplateArguments(Ctx, As, AX->getTypeConstraintArguments(),
13653 AY->getTypeConstraintArguments())) {
13654 CD = nullptr; // The arguments differ, so make it unconstrained.
13655 As.clear();
13656 }
13657
13658 // Both auto types can't be dependent, otherwise they wouldn't have been
13659 // sugar. This implies they can't contain unexpanded packs either.
13660 return Ctx.getAutoType(Ctx.getQualifiedType(Underlying), AX->getKeyword(),
13661 /*IsDependent=*/false, /*IsPack=*/false, CD, As);
13662 }
13663 case Type::PackIndexing:
13664 case Type::Decltype:
13665 return QualType();
13666 case Type::DeducedTemplateSpecialization:
13667 // FIXME: Try to merge these.
13668 return QualType();
13669
13670 case Type::Elaborated: {
13671 const auto *EX = cast<ElaboratedType>(X), *EY = cast<ElaboratedType>(Y);
13672 return Ctx.getElaboratedType(
13673 ::getCommonTypeKeyword(EX, EY), ::getCommonNNS(Ctx, EX, EY),
13674 Ctx.getQualifiedType(Underlying),
13675 ::getCommonDecl(EX->getOwnedTagDecl(), EY->getOwnedTagDecl()));
13676 }
13677 case Type::MacroQualified: {
13678 const auto *MX = cast<MacroQualifiedType>(X),
13679 *MY = cast<MacroQualifiedType>(Y);
13680 const IdentifierInfo *IX = MX->getMacroIdentifier();
13681 if (IX != MY->getMacroIdentifier())
13682 return QualType();
13683 return Ctx.getMacroQualifiedType(Ctx.getQualifiedType(Underlying), IX);
13684 }
13685 case Type::SubstTemplateTypeParm: {
13686 const auto *SX = cast<SubstTemplateTypeParmType>(X),
13687 *SY = cast<SubstTemplateTypeParmType>(Y);
13688 Decl *CD =
13689 ::getCommonDecl(SX->getAssociatedDecl(), SY->getAssociatedDecl());
13690 if (!CD)
13691 return QualType();
13692 unsigned Index = SX->getIndex();
13693 if (Index != SY->getIndex())
13694 return QualType();
13695 auto PackIndex = SX->getPackIndex();
13696 if (PackIndex != SY->getPackIndex())
13697 return QualType();
13698 return Ctx.getSubstTemplateTypeParmType(Ctx.getQualifiedType(Underlying),
13699 CD, Index, PackIndex);
13700 }
13701 case Type::ObjCTypeParam:
13702 // FIXME: Try to merge these.
13703 return QualType();
13704 case Type::Paren:
13705 return Ctx.getParenType(Ctx.getQualifiedType(Underlying));
13706
13707 case Type::TemplateSpecialization: {
13708 const auto *TX = cast<TemplateSpecializationType>(X),
13709 *TY = cast<TemplateSpecializationType>(Y);
13710 TemplateName CTN = ::getCommonTemplateName(Ctx, TX->getTemplateName(),
13711 TY->getTemplateName());
13712 if (!CTN.getAsVoidPointer())
13713 return QualType();
13715 if (getCommonTemplateArguments(Ctx, Args, TX->template_arguments(),
13716 TY->template_arguments()))
13717 return QualType();
13718 return Ctx.getTemplateSpecializationType(CTN, Args,
13719 Ctx.getQualifiedType(Underlying));
13720 }
13721 case Type::Typedef: {
13722 const auto *TX = cast<TypedefType>(X), *TY = cast<TypedefType>(Y);
13723 const TypedefNameDecl *CD = ::getCommonDecl(TX->getDecl(), TY->getDecl());
13724 if (!CD)
13725 return QualType();
13726 return Ctx.getTypedefType(CD, Ctx.getQualifiedType(Underlying));
13727 }
13728 case Type::TypeOf: {
13729 // The common sugar between two typeof expressions, where one is
13730 // potentially a typeof_unqual and the other is not, we unify to the
13731 // qualified type as that retains the most information along with the type.
13732 // We only return a typeof_unqual type when both types are unqual types.
13734 if (cast<TypeOfType>(X)->getKind() == cast<TypeOfType>(Y)->getKind() &&
13735 cast<TypeOfType>(X)->getKind() == TypeOfKind::Unqualified)
13737 return Ctx.getTypeOfType(Ctx.getQualifiedType(Underlying), Kind);
13738 }
13739 case Type::TypeOfExpr:
13740 return QualType();
13741
13742 case Type::UnaryTransform: {
13743 const auto *UX = cast<UnaryTransformType>(X),
13744 *UY = cast<UnaryTransformType>(Y);
13745 UnaryTransformType::UTTKind KX = UX->getUTTKind();
13746 if (KX != UY->getUTTKind())
13747 return QualType();
13748 QualType BX = UX->getBaseType(), BY = UY->getBaseType();
13749 if (!Ctx.hasSameType(BX, BY))
13750 return QualType();
13751 // FIXME: It's inefficient to have to unify the base types.
13752 return Ctx.getUnaryTransformType(Ctx.getCommonSugaredType(BX, BY),
13753 Ctx.getQualifiedType(Underlying), KX);
13754 }
13755 case Type::Using: {
13756 const auto *UX = cast<UsingType>(X), *UY = cast<UsingType>(Y);
13757 const UsingShadowDecl *CD =
13758 ::getCommonDecl(UX->getFoundDecl(), UY->getFoundDecl());
13759 if (!CD)
13760 return QualType();
13761 return Ctx.getUsingType(CD, Ctx.getQualifiedType(Underlying));
13762 }
13763 case Type::CountAttributed: {
13764 const auto *DX = cast<CountAttributedType>(X),
13765 *DY = cast<CountAttributedType>(Y);
13766 if (DX->isCountInBytes() != DY->isCountInBytes())
13767 return QualType();
13768 if (DX->isOrNull() != DY->isOrNull())
13769 return QualType();
13770 Expr *CEX = DX->getCountExpr();
13771 Expr *CEY = DY->getCountExpr();
13772 llvm::ArrayRef<clang::TypeCoupledDeclRefInfo> CDX = DX->getCoupledDecls();
13773 if (Ctx.hasSameExpr(CEX, CEY))
13774 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX,
13775 DX->isCountInBytes(), DX->isOrNull(),
13776 CDX);
13777 if (!CEX->isIntegerConstantExpr(Ctx) || !CEY->isIntegerConstantExpr(Ctx))
13778 return QualType();
13779 // Two declarations with the same integer constant may still differ in their
13780 // expression pointers, so we need to evaluate them.
13781 llvm::APSInt VX = *CEX->getIntegerConstantExpr(Ctx);
13782 llvm::APSInt VY = *CEY->getIntegerConstantExpr(Ctx);
13783 if (VX != VY)
13784 return QualType();
13785 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX,
13786 DX->isCountInBytes(), DX->isOrNull(),
13787 CDX);
13788 }
13789 }
13790 llvm_unreachable("Unhandled Type Class");
13791}
13792
13793static auto unwrapSugar(SplitQualType &T, Qualifiers &QTotal) {
13795 while (true) {
13796 QTotal.addConsistentQualifiers(T.Quals);
13798 if (NT == QualType(T.Ty, 0))
13799 break;
13800 R.push_back(T);
13801 T = NT.split();
13802 }
13803 return R;
13804}
13805
13807 bool Unqualified) {
13808 assert(Unqualified ? hasSameUnqualifiedType(X, Y) : hasSameType(X, Y));
13809 if (X == Y)
13810 return X;
13811 if (!Unqualified) {
13812 if (X.isCanonical())
13813 return X;
13814 if (Y.isCanonical())
13815 return Y;
13816 }
13817
13818 SplitQualType SX = X.split(), SY = Y.split();
13819 Qualifiers QX, QY;
13820 // Desugar SX and SY, setting the sugar and qualifiers aside into Xs and Ys,
13821 // until we reach their underlying "canonical nodes". Note these are not
13822 // necessarily canonical types, as they may still have sugared properties.
13823 // QX and QY will store the sum of all qualifiers in Xs and Ys respectively.
13824 auto Xs = ::unwrapSugar(SX, QX), Ys = ::unwrapSugar(SY, QY);
13825 if (SX.Ty != SY.Ty) {
13826 // The canonical nodes differ. Build a common canonical node out of the two,
13827 // unifying their sugar. This may recurse back here.
13828 SX.Ty =
13829 ::getCommonNonSugarTypeNode(*this, SX.Ty, QX, SY.Ty, QY).getTypePtr();
13830 } else {
13831 // The canonical nodes were identical: We may have desugared too much.
13832 // Add any common sugar back in.
13833 while (!Xs.empty() && !Ys.empty() && Xs.back().Ty == Ys.back().Ty) {
13834 QX -= SX.Quals;
13835 QY -= SY.Quals;
13836 SX = Xs.pop_back_val();
13837 SY = Ys.pop_back_val();
13838 }
13839 }
13840 if (Unqualified)
13842 else
13843 assert(QX == QY);
13844
13845 // Even though the remaining sugar nodes in Xs and Ys differ, some may be
13846 // related. Walk up these nodes, unifying them and adding the result.
13847 while (!Xs.empty() && !Ys.empty()) {
13848 auto Underlying = SplitQualType(
13849 SX.Ty, Qualifiers::removeCommonQualifiers(SX.Quals, SY.Quals));
13850 SX = Xs.pop_back_val();
13851 SY = Ys.pop_back_val();
13852 SX.Ty = ::getCommonSugarTypeNode(*this, SX.Ty, SY.Ty, Underlying)
13854 // Stop at the first pair which is unrelated.
13855 if (!SX.Ty) {
13856 SX.Ty = Underlying.Ty;
13857 break;
13858 }
13859 QX -= Underlying.Quals;
13860 };
13861
13862 // Add back the missing accumulated qualifiers, which were stripped off
13863 // with the sugar nodes we could not unify.
13864 QualType R = getQualifiedType(SX.Ty, QX);
13865 assert(Unqualified ? hasSameUnqualifiedType(R, X) : hasSameType(R, X));
13866 return R;
13867}
13868
13870 assert(Ty->isFixedPointType());
13871
13873 return Ty;
13874
13875 switch (Ty->castAs<BuiltinType>()->getKind()) {
13876 default:
13877 llvm_unreachable("Not a saturated fixed point type!");
13878 case BuiltinType::SatShortAccum:
13879 return ShortAccumTy;
13880 case BuiltinType::SatAccum:
13881 return AccumTy;
13882 case BuiltinType::SatLongAccum:
13883 return LongAccumTy;
13884 case BuiltinType::SatUShortAccum:
13885 return UnsignedShortAccumTy;
13886 case BuiltinType::SatUAccum:
13887 return UnsignedAccumTy;
13888 case BuiltinType::SatULongAccum:
13889 return UnsignedLongAccumTy;
13890 case BuiltinType::SatShortFract:
13891 return ShortFractTy;
13892 case BuiltinType::SatFract:
13893 return FractTy;
13894 case BuiltinType::SatLongFract:
13895 return LongFractTy;
13896 case BuiltinType::SatUShortFract:
13897 return UnsignedShortFractTy;
13898 case BuiltinType::SatUFract:
13899 return UnsignedFractTy;
13900 case BuiltinType::SatULongFract:
13901 return UnsignedLongFractTy;
13902 }
13903}
13904
13906 assert(Ty->isFixedPointType());
13907
13908 if (Ty->isSaturatedFixedPointType()) return Ty;
13909
13910 switch (Ty->castAs<BuiltinType>()->getKind()) {
13911 default:
13912 llvm_unreachable("Not a fixed point type!");
13913 case BuiltinType::ShortAccum:
13914 return SatShortAccumTy;
13915 case BuiltinType::Accum:
13916 return SatAccumTy;
13917 case BuiltinType::LongAccum:
13918 return SatLongAccumTy;
13919 case BuiltinType::UShortAccum:
13921 case BuiltinType::UAccum:
13922 return SatUnsignedAccumTy;
13923 case BuiltinType::ULongAccum:
13925 case BuiltinType::ShortFract:
13926 return SatShortFractTy;
13927 case BuiltinType::Fract:
13928 return SatFractTy;
13929 case BuiltinType::LongFract:
13930 return SatLongFractTy;
13931 case BuiltinType::UShortFract:
13933 case BuiltinType::UFract:
13934 return SatUnsignedFractTy;
13935 case BuiltinType::ULongFract:
13937 }
13938}
13939
13941 if (LangOpts.OpenCL)
13943
13944 if (LangOpts.CUDA)
13946
13947 return getLangASFromTargetAS(AS);
13948}
13949
13950// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
13951// doesn't include ASTContext.h
13952template
13954 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
13956 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
13957 const clang::ASTContext &Ctx, Decl *Value);
13958
13960 assert(Ty->isFixedPointType());
13961
13962 const TargetInfo &Target = getTargetInfo();
13963 switch (Ty->castAs<BuiltinType>()->getKind()) {
13964 default:
13965 llvm_unreachable("Not a fixed point type!");
13966 case BuiltinType::ShortAccum:
13967 case BuiltinType::SatShortAccum:
13968 return Target.getShortAccumScale();
13969 case BuiltinType::Accum:
13970 case BuiltinType::SatAccum:
13971 return Target.getAccumScale();
13972 case BuiltinType::LongAccum:
13973 case BuiltinType::SatLongAccum:
13974 return Target.getLongAccumScale();
13975 case BuiltinType::UShortAccum:
13976 case BuiltinType::SatUShortAccum:
13977 return Target.getUnsignedShortAccumScale();
13978 case BuiltinType::UAccum:
13979 case BuiltinType::SatUAccum:
13980 return Target.getUnsignedAccumScale();
13981 case BuiltinType::ULongAccum:
13982 case BuiltinType::SatULongAccum:
13983 return Target.getUnsignedLongAccumScale();
13984 case BuiltinType::ShortFract:
13985 case BuiltinType::SatShortFract:
13986 return Target.getShortFractScale();
13987 case BuiltinType::Fract:
13988 case BuiltinType::SatFract:
13989 return Target.getFractScale();
13990 case BuiltinType::LongFract:
13991 case BuiltinType::SatLongFract:
13992 return Target.getLongFractScale();
13993 case BuiltinType::UShortFract:
13994 case BuiltinType::SatUShortFract:
13995 return Target.getUnsignedShortFractScale();
13996 case BuiltinType::UFract:
13997 case BuiltinType::SatUFract:
13998 return Target.getUnsignedFractScale();
13999 case BuiltinType::ULongFract:
14000 case BuiltinType::SatULongFract:
14001 return Target.getUnsignedLongFractScale();
14002 }
14003}
14004
14006 assert(Ty->isFixedPointType());
14007
14008 const TargetInfo &Target = getTargetInfo();
14009 switch (Ty->castAs<BuiltinType>()->getKind()) {
14010 default:
14011 llvm_unreachable("Not a fixed point type!");
14012 case BuiltinType::ShortAccum:
14013 case BuiltinType::SatShortAccum:
14014 return Target.getShortAccumIBits();
14015 case BuiltinType::Accum:
14016 case BuiltinType::SatAccum:
14017 return Target.getAccumIBits();
14018 case BuiltinType::LongAccum:
14019 case BuiltinType::SatLongAccum:
14020 return Target.getLongAccumIBits();
14021 case BuiltinType::UShortAccum:
14022 case BuiltinType::SatUShortAccum:
14023 return Target.getUnsignedShortAccumIBits();
14024 case BuiltinType::UAccum:
14025 case BuiltinType::SatUAccum:
14026 return Target.getUnsignedAccumIBits();
14027 case BuiltinType::ULongAccum:
14028 case BuiltinType::SatULongAccum:
14029 return Target.getUnsignedLongAccumIBits();
14030 case BuiltinType::ShortFract:
14031 case BuiltinType::SatShortFract:
14032 case BuiltinType::Fract:
14033 case BuiltinType::SatFract:
14034 case BuiltinType::LongFract:
14035 case BuiltinType::SatLongFract:
14036 case BuiltinType::UShortFract:
14037 case BuiltinType::SatUShortFract:
14038 case BuiltinType::UFract:
14039 case BuiltinType::SatUFract:
14040 case BuiltinType::ULongFract:
14041 case BuiltinType::SatULongFract:
14042 return 0;
14043 }
14044}
14045
14046llvm::FixedPointSemantics
14048 assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
14049 "Can only get the fixed point semantics for a "
14050 "fixed point or integer type.");
14051 if (Ty->isIntegerType())
14052 return llvm::FixedPointSemantics::GetIntegerSemantics(
14053 getIntWidth(Ty), Ty->isSignedIntegerType());
14054
14055 bool isSigned = Ty->isSignedFixedPointType();
14056 return llvm::FixedPointSemantics(
14057 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
14059 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
14060}
14061
14062llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
14063 assert(Ty->isFixedPointType());
14064 return llvm::APFixedPoint::getMax(getFixedPointSemantics(Ty));
14065}
14066
14067llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
14068 assert(Ty->isFixedPointType());
14069 return llvm::APFixedPoint::getMin(getFixedPointSemantics(Ty));
14070}
14071
14073 assert(Ty->isUnsignedFixedPointType() &&
14074 "Expected unsigned fixed point type");
14075
14076 switch (Ty->castAs<BuiltinType>()->getKind()) {
14077 case BuiltinType::UShortAccum:
14078 return ShortAccumTy;
14079 case BuiltinType::UAccum:
14080 return AccumTy;
14081 case BuiltinType::ULongAccum:
14082 return LongAccumTy;
14083 case BuiltinType::SatUShortAccum:
14084 return SatShortAccumTy;
14085 case BuiltinType::SatUAccum:
14086 return SatAccumTy;
14087 case BuiltinType::SatULongAccum:
14088 return SatLongAccumTy;
14089 case BuiltinType::UShortFract:
14090 return ShortFractTy;
14091 case BuiltinType::UFract:
14092 return FractTy;
14093 case BuiltinType::ULongFract:
14094 return LongFractTy;
14095 case BuiltinType::SatUShortFract:
14096 return SatShortFractTy;
14097 case BuiltinType::SatUFract:
14098 return SatFractTy;
14099 case BuiltinType::SatULongFract:
14100 return SatLongFractTy;
14101 default:
14102 llvm_unreachable("Unexpected unsigned fixed point type");
14103 }
14104}
14105
14106// Given a list of FMV features, return a concatenated list of the
14107// corresponding backend features (which may contain duplicates).
14108static std::vector<std::string> getFMVBackendFeaturesFor(
14109 const llvm::SmallVectorImpl<StringRef> &FMVFeatStrings) {
14110 std::vector<std::string> BackendFeats;
14111 for (StringRef F : FMVFeatStrings)
14112 if (auto FMVExt = llvm::AArch64::parseFMVExtension(F))
14113 for (StringRef F : FMVExt->getImpliedFeatures())
14114 BackendFeats.push_back(F.str());
14115 return BackendFeats;
14116}
14117
14119ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const {
14120 assert(TD != nullptr);
14121 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(TD->getFeaturesStr());
14122
14123 llvm::erase_if(ParsedAttr.Features, [&](const std::string &Feat) {
14124 return !Target->isValidFeatureName(StringRef{Feat}.substr(1));
14125 });
14126 return ParsedAttr;
14127}
14128
14129void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
14130 const FunctionDecl *FD) const {
14131 if (FD)
14132 getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD));
14133 else
14134 Target->initFeatureMap(FeatureMap, getDiagnostics(),
14135 Target->getTargetOpts().CPU,
14136 Target->getTargetOpts().Features);
14137}
14138
14139// Fills in the supplied string map with the set of target features for the
14140// passed in function.
14141void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
14142 GlobalDecl GD) const {
14143 StringRef TargetCPU = Target->getTargetOpts().CPU;
14144 const FunctionDecl *FD = GD.getDecl()->getAsFunction();
14145 if (const auto *TD = FD->getAttr<TargetAttr>()) {
14147
14148 // Make a copy of the features as passed on the command line into the
14149 // beginning of the additional features from the function to override.
14150 // AArch64 handles command line option features in parseTargetAttr().
14151 if (!Target->getTriple().isAArch64())
14152 ParsedAttr.Features.insert(
14153 ParsedAttr.Features.begin(),
14154 Target->getTargetOpts().FeaturesAsWritten.begin(),
14155 Target->getTargetOpts().FeaturesAsWritten.end());
14156
14157 if (ParsedAttr.CPU != "" && Target->isValidCPUName(ParsedAttr.CPU))
14158 TargetCPU = ParsedAttr.CPU;
14159
14160 // Now populate the feature map, first with the TargetCPU which is either
14161 // the default or a new one from the target attribute string. Then we'll use
14162 // the passed in features (FeaturesAsWritten) along with the new ones from
14163 // the attribute.
14164 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU,
14165 ParsedAttr.Features);
14166 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
14168 Target->getCPUSpecificCPUDispatchFeatures(
14169 SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp);
14170 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
14171 Features.insert(Features.begin(),
14172 Target->getTargetOpts().FeaturesAsWritten.begin(),
14173 Target->getTargetOpts().FeaturesAsWritten.end());
14174 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14175 } else if (const auto *TC = FD->getAttr<TargetClonesAttr>()) {
14176 if (Target->getTriple().isAArch64()) {
14178 TC->getFeatures(Feats, GD.getMultiVersionIndex());
14179 std::vector<std::string> Features = getFMVBackendFeaturesFor(Feats);
14180 Features.insert(Features.begin(),
14181 Target->getTargetOpts().FeaturesAsWritten.begin(),
14182 Target->getTargetOpts().FeaturesAsWritten.end());
14183 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14184 } else {
14185 std::vector<std::string> Features;
14186 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
14187 if (VersionStr.starts_with("arch="))
14188 TargetCPU = VersionStr.drop_front(sizeof("arch=") - 1);
14189 else if (VersionStr != "default")
14190 Features.push_back((StringRef{"+"} + VersionStr).str());
14191 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14192 }
14193 } else if (const auto *TV = FD->getAttr<TargetVersionAttr>()) {
14195 TV->getFeatures(Feats);
14196 std::vector<std::string> Features = getFMVBackendFeaturesFor(Feats);
14197 Features.insert(Features.begin(),
14198 Target->getTargetOpts().FeaturesAsWritten.begin(),
14199 Target->getTargetOpts().FeaturesAsWritten.end());
14200 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14201 } else {
14202 FeatureMap = Target->getTargetOpts().FeatureMap;
14203 }
14204}
14205
14207 OMPTraitInfoVector.emplace_back(new OMPTraitInfo());
14208 return *OMPTraitInfoVector.back();
14209}
14210
14213 const ASTContext::SectionInfo &Section) {
14214 if (Section.Decl)
14215 return DB << Section.Decl;
14216 return DB << "a prior #pragma section";
14217}
14218
14220 bool IsInternalVar =
14221 isa<VarDecl>(D) &&
14222 basicGVALinkageForVariable(*this, cast<VarDecl>(D)) == GVA_Internal;
14223 bool IsExplicitDeviceVar = (D->hasAttr<CUDADeviceAttr>() &&
14224 !D->getAttr<CUDADeviceAttr>()->isImplicit()) ||
14225 (D->hasAttr<CUDAConstantAttr>() &&
14226 !D->getAttr<CUDAConstantAttr>()->isImplicit());
14227 // CUDA/HIP: managed variables need to be externalized since it is
14228 // a declaration in IR, therefore cannot have internal linkage. Kernels in
14229 // anonymous name space needs to be externalized to avoid duplicate symbols.
14230 return (IsInternalVar &&
14231 (D->hasAttr<HIPManagedAttr>() || IsExplicitDeviceVar)) ||
14232 (D->hasAttr<CUDAGlobalAttr>() &&
14233 basicGVALinkageForFunction(*this, cast<FunctionDecl>(D)) ==
14234 GVA_Internal);
14235}
14236
14238 return mayExternalize(D) &&
14239 (D->hasAttr<HIPManagedAttr>() || D->hasAttr<CUDAGlobalAttr>() ||
14240 CUDADeviceVarODRUsedByHost.count(cast<VarDecl>(D)));
14241}
14242
14243StringRef ASTContext::getCUIDHash() const {
14244 if (!CUIDHash.empty())
14245 return CUIDHash;
14246 if (LangOpts.CUID.empty())
14247 return StringRef();
14248 CUIDHash = llvm::utohexstr(llvm::MD5Hash(LangOpts.CUID), /*LowerCase=*/true);
14249 return CUIDHash;
14250}
14251
14252const CXXRecordDecl *
14254 assert(ThisClass);
14255 assert(ThisClass->isPolymorphic());
14256 const CXXRecordDecl *PrimaryBase = ThisClass;
14257 while (1) {
14258 assert(PrimaryBase);
14259 assert(PrimaryBase->isPolymorphic());
14260 auto &Layout = getASTRecordLayout(PrimaryBase);
14261 auto Base = Layout.getPrimaryBase();
14262 if (!Base || Base == PrimaryBase || !Base->isPolymorphic())
14263 break;
14264 PrimaryBase = Base;
14265 }
14266 return PrimaryBase;
14267}
14268
14270 StringRef MangledName) {
14271 auto *Method = cast<CXXMethodDecl>(VirtualMethodDecl.getDecl());
14272 assert(Method->isVirtual());
14273 bool DefaultIncludesPointerAuth =
14274 LangOpts.PointerAuthCalls || LangOpts.PointerAuthIntrinsics;
14275
14276 if (!DefaultIncludesPointerAuth)
14277 return true;
14278
14279 auto Existing = ThunksToBeAbbreviated.find(VirtualMethodDecl);
14280 if (Existing != ThunksToBeAbbreviated.end())
14281 return Existing->second.contains(MangledName.str());
14282
14283 std::unique_ptr<MangleContext> Mangler(createMangleContext());
14284 llvm::StringMap<llvm::SmallVector<std::string, 2>> Thunks;
14285 auto VtableContext = getVTableContext();
14286 if (const auto *ThunkInfos = VtableContext->getThunkInfo(VirtualMethodDecl)) {
14287 auto *Destructor = dyn_cast<CXXDestructorDecl>(Method);
14288 for (const auto &Thunk : *ThunkInfos) {
14289 SmallString<256> ElidedName;
14290 llvm::raw_svector_ostream ElidedNameStream(ElidedName);
14291 if (Destructor)
14292 Mangler->mangleCXXDtorThunk(Destructor, VirtualMethodDecl.getDtorType(),
14293 Thunk, /* elideOverrideInfo */ true,
14294 ElidedNameStream);
14295 else
14296 Mangler->mangleThunk(Method, Thunk, /* elideOverrideInfo */ true,
14297 ElidedNameStream);
14298 SmallString<256> MangledName;
14299 llvm::raw_svector_ostream mangledNameStream(MangledName);
14300 if (Destructor)
14301 Mangler->mangleCXXDtorThunk(Destructor, VirtualMethodDecl.getDtorType(),
14302 Thunk, /* elideOverrideInfo */ false,
14303 mangledNameStream);
14304 else
14305 Mangler->mangleThunk(Method, Thunk, /* elideOverrideInfo */ false,
14306 mangledNameStream);
14307
14308 if (Thunks.find(ElidedName) == Thunks.end())
14309 Thunks[ElidedName] = {};
14310 Thunks[ElidedName].push_back(std::string(MangledName));
14311 }
14312 }
14313 llvm::StringSet<> SimplifiedThunkNames;
14314 for (auto &ThunkList : Thunks) {
14315 llvm::sort(ThunkList.second);
14316 SimplifiedThunkNames.insert(ThunkList.second[0]);
14317 }
14318 bool Result = SimplifiedThunkNames.contains(MangledName);
14319 ThunksToBeAbbreviated[VirtualMethodDecl] = std::move(SimplifiedThunkNames);
14320 return Result;
14321}
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 getCommonTypes(ASTContext &Ctx, ArrayRef< QualType > Xs, ArrayRef< QualType > Ys, bool Unqualified=false)
static auto getCanonicalTemplateArguments(const ASTContext &C, ArrayRef< TemplateArgument > Args, bool &AnyNonCanonArgs)
static char getObjCEncodingForPrimitiveType(const ASTContext *C, const BuiltinType *BT)
static bool NeedsInjectedClassNameType(const RecordDecl *D)
#define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS)
static bool unionHasUniqueObjectRepresentations(const ASTContext &Context, const RecordDecl *RD, bool CheckIfTriviallyCopyable)
static NamespaceDecl * getNamespace(const NestedNameSpecifier *X)
static TypedefDecl * CreateHexagonBuiltinVaListDecl(const ASTContext *Context)
#define CANONICAL_TYPE(Class)
static NestedNameSpecifier * getCommonNNS(ASTContext &Ctx, const T *X, const T *Y)
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 uint64_t getSVETypeSize(ASTContext &Context, const BuiltinType *Ty)
getSVETypeSize - Return SVE vector or predicate register size.
#define SUGAR_FREE_TYPE(Class)
static bool getCommonTemplateArguments(ASTContext &Ctx, SmallVectorImpl< TemplateArgument > &R, ArrayRef< TemplateArgument > Xs, ArrayRef< TemplateArgument > Ys)
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 TemplateName getCommonTemplateNameChecked(ASTContext &Ctx, TemplateName X, TemplateName Y)
static const Decl & adjustDeclToTemplate(const Decl &D)
If we have a 'templated' declaration for a template, adjust 'D' to refer to the actual template.
Definition: ASTContext.cpp:337
static int CmpProtocolNames(ObjCProtocolDecl *const *LHS, ObjCProtocolDecl *const *RHS)
CmpProtocolNames - Comparison predicate for sorting protocols alphabetically.
static QualType getCommonElementType(ASTContext &Ctx, const T *X, const T *Y)
static TypedefDecl * CreatePowerABIBuiltinVaListDecl(const ASTContext *Context)
static auto getCommonSizeModifier(const ArrayType *X, const ArrayType *Y)
static std::optional< int64_t > structHasUniqueObjectRepresentations(const ASTContext &Context, const RecordDecl *RD, bool CheckIfTriviallyCopyable)
static TemplateName getCommonTemplateName(ASTContext &Ctx, TemplateName X, TemplateName Y)
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 TypedefDecl * CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context)
static int64_t getSubobjectOffset(const FieldDecl *Field, const ASTContext &Context, const clang::ASTRecordLayout &)
static TypedefDecl * CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context)
static TypedefDecl * CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context)
static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET, QualType other, bool isBlockReturnType)
Given that we have an enum type and a non-enum type, try to merge them.
static GVALinkage adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D, GVALinkage L)
Adjust the GVALinkage for a declaration based on what an external AST source knows about whether ther...
static TypedefDecl * CreateSystemZBuiltinVaListDecl(const ASTContext *Context)
static std::optional< int64_t > getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context, bool CheckIfTriviallyCopyable)
static GVALinkage basicGVALinkageForFunction(const ASTContext &Context, const FunctionDecl *FD)
#define NON_UNIQUE_TYPE(Class)
static TypedefDecl * CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context)
static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI, const LangOptions &LangOpts)
Definition: ASTContext.cpp:859
static auto getCommonIndexTypeCVRQualifiers(const ArrayType *X, const ArrayType *Y)
#define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS)
static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context, ASTContext::GetBuiltinTypeError &Error, bool &RequiresICE, bool AllowTypeModifiers)
DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the pointer over the consume...
FloatingRank
Definition: ASTContext.cpp:107
@ FloatRank
Definition: ASTContext.cpp:111
@ LongDoubleRank
Definition: ASTContext.cpp:113
@ Float16Rank
Definition: ASTContext.cpp:109
@ Ibm128Rank
Definition: ASTContext.cpp:115
@ Float128Rank
Definition: ASTContext.cpp:114
@ BFloat16Rank
Definition: ASTContext.cpp:108
@ HalfRank
Definition: ASTContext.cpp:110
@ DoubleRank
Definition: ASTContext.cpp:112
static TypedefDecl * CreateCharPtrBuiltinVaListDecl(const ASTContext *Context)
static void mergeTypeLists(ASTContext &Ctx, SmallVectorImpl< QualType > &Out, ArrayRef< QualType > X, ArrayRef< QualType > Y)
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 TemplateArgument getCommonTemplateArgument(ASTContext &Ctx, const TemplateArgument &X, const TemplateArgument &Y)
static auto * getCommonSizeExpr(ASTContext &Ctx, T *X, T *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 char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET)
static QualType getCommonArrayElementType(ASTContext &Ctx, const T *X, Qualifiers &QX, const T *Y, Qualifiers &QY)
static QualType getCommonPointeeType(ASTContext &Ctx, const T *X, const T *Y)
static uint64_t getRVVTypeSize(ASTContext &Context, const BuiltinType *Ty)
getRVVTypeSize - Return RVV vector register size.
static auto unwrapSugar(SplitQualType &T, Qualifiers &QTotal)
static int compareObjCProtocolsByName(ObjCProtocolDecl *const *lhs, ObjCProtocolDecl *const *rhs)
Comparison routine for Objective-C protocols to be used with llvm::array_pod_sort.
static QualType getCommonNonSugarTypeNode(ASTContext &Ctx, const Type *X, Qualifiers &QX, const Type *Y, Qualifiers &QY)
static QualType getCommonSugarTypeNode(ASTContext &Ctx, const Type *X, const Type *Y, SplitQualType Underlying)
static bool isSameQualifier(const NestedNameSpecifier *X, const NestedNameSpecifier *Y)
static std::string charUnitsToString(const CharUnits &CU)
static bool hasAnyPackExpansions(ArrayRef< TemplateArgument > Args)
static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod, SmallVectorImpl< const NamedDecl * > &Redeclared)
Definition: ASTContext.cpp:481
static SmallVector< SourceLocation, 2 > getDeclLocsForCommentSearch(const Decl *D, SourceManager &SourceMgr)
Definition: ASTContext.cpp:121
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)
#define UNEXPECTED_TYPE(Class, Kind)
static TypedefDecl * CreateVaListDecl(const ASTContext *Context, TargetInfo::BuiltinVaListKind Kind)
static std::vector< std::string > getFMVBackendFeaturesFor(const llvm::SmallVectorImpl< StringRef > &FMVFeatStrings)
static ElaboratedTypeKeyword getCommonTypeKeyword(const T *X, const T *Y)
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3341
NodeId Parent
Definition: ASTDiff.cpp:191
StringRef P
Provides definitions for the various language-specific address spaces.
static bool isUnsigned(SValBuilder &SVB, NonLoc Value)
#define SM(sm)
Definition: Cuda.cpp:83
static constexpr Builtin::Info BuiltinInfo[]
Definition: Builtins.cpp:32
Defines enum values for all the target-independent builtin functions.
static bool CanThrow(Expr *E, ASTContext &Ctx)
Definition: CFG.cpp:2679
const Decl * D
IndirectLocalPath & Path
Expr * E
Defines the clang::CommentOptions interface.
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:1171
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.
Defines Expressions and AST nodes for C++2a concepts.
StringRef Text
Definition: Format.cpp:3015
unsigned Iter
Definition: HTMLLogger.cpp:154
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
static const Decl * getCanonicalDecl(const Decl *D)
#define X(type, name)
Definition: Value.h:143
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::LangOptions interface.
llvm::MachO::Target Target
Definition: MachO.h:51
llvm::MachO::Record Record
Definition: MachO.h:31
static bool hasFeature(StringRef Feature, const LangOptions &LangOpts, const TargetInfo &Target)
Determine whether a translation unit built using the current language options has the given feature.
Definition: Module.cpp:100
Defines the clang::Module class, which describes a module in the source code.
Defines types useful for describing an Objective-C runtime.
static bool compare(const PathDiagnostic &X, const PathDiagnostic &Y)
static QualType getUnderlyingType(const SubRegion *R)
uint32_t Id
Definition: SemaARM.cpp:1144
SourceRange Range
Definition: SemaObjC.cpp:758
SourceLocation Loc
Definition: SemaObjC.cpp:759
Defines the clang::SourceLocation class and associated facilities.
Defines the SourceManager interface.
Defines various enumerations that describe declaration and type specifiers.
This file defines OpenACC AST classes for statement-level contructs.
static QualType getPointeeType(const MemRegion *R)
Defines the TargetCXXABI class, which abstracts details of the C++ ABI that we're targeting.
Defines the clang::TypeLoc interface and its subclasses.
static const TemplateArgument & getArgument(const TemplateArgument &A)
C Language Family Type Representation.
SourceLocation Begin
__device__ __2f16 float c
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
bool isMemberPointerToDerivedMember() const
Definition: APValue.cpp:1064
const ValueDecl * getMemberPointerDecl() const
Definition: APValue.cpp:1057
ArrayRef< const CXXRecordDecl * > getMemberPointerPath() const
Definition: APValue.cpp:1071
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:187
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.
QualType getUsingType(const UsingShadowDecl *Found, QualType Underlying) const
CanQualType AccumTy
Definition: ASTContext.h:1132
BuiltinVectorTypeInfo getBuiltinVectorTypeInfo(const BuiltinType *VecTy) const
Returns the element type, element count and number of vectors (in case of tuple) for a builtin vector...
bool ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl, const ObjCMethodDecl *MethodImp)
CanQualType ObjCBuiltinSelTy
Definition: ASTContext.h:1151
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1101
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2825
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.
bool areLaxCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible SVE vector types, false otherwise.
llvm::PointerUnion< VarTemplateDecl *, MemberSpecializationInfo * > TemplateOrSpecializationInfo
A type synonym for the TemplateOrInstantiation mapping.
Definition: ASTContext.h:489
LangAS getOpenCLTypeAddrSpace(const Type *T) const
Get address space for OpenCL type.
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
void InitBuiltinTypes(const TargetInfo &Target, const TargetInfo *AuxTarget=nullptr)
Initialize built-in types.
ParentMapContext & getParentMapContext()
Returns the dynamic AST node parent map context.
Definition: ASTContext.cpp:853
QualType getParenType(QualType NamedType) const
size_t getSideTableAllocatedMemory() const
Return the total memory used for various side tables.
MemberSpecializationInfo * getInstantiatedFromStaticDataMember(const VarDecl *Var)
If this variable is an instantiated static data member of a class template specialization,...
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type.
CanQualType ARCUnbridgedCastTy
Definition: ASTContext.h:1150
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.
llvm::DenseMap< const Decl *, comments::FullComment * > ParsedComments
Mapping from declarations to parsed comments attached to any redeclaration.
Definition: ASTContext.h:856
unsigned getManglingNumber(const NamedDecl *ND, bool ForAuxTarget=false) const
CanQualType LongTy
Definition: ASTContext.h:1128
void UnwrapSimilarArrayTypes(QualType &T1, QualType &T2, bool AllowPiMismatch=true)
Attempt to unwrap two types that may both be array types with the same bound (or both be array types ...
unsigned getIntWidth(QualType T) const
CanQualType getCanonicalParamType(QualType T) const
Return the canonical parameter type corresponding to the specific potentially non-canonical one.
QualType getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr, QualType Wrapped)
const FunctionType * adjustFunctionType(const FunctionType *Fn, FunctionType::ExtInfo EInfo)
Change the ExtInfo on a function type.
TemplateOrSpecializationInfo getTemplateOrSpecializationInfo(const VarDecl *Var)
CanQualType WIntTy
Definition: ASTContext.h:1124
QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType) const
@ Weak
Weak definition of inline variable.
@ WeakUnknown
Weak for now, might become strong later in this TU.
void setObjCConstantStringInterface(ObjCInterfaceDecl *Decl)
TypedefDecl * getObjCClassDecl() const
Retrieve the typedef declaration corresponding to the predefined Objective-C 'Class' type.
TypedefNameDecl * getTypedefNameForUnnamedTagDecl(const TagDecl *TD)
TypedefDecl * getCFConstantStringDecl() const
CanQualType Int128Ty
Definition: ASTContext.h:1128
CanQualType SatUnsignedFractTy
Definition: ASTContext.h:1141
BuiltinTemplateDecl * getMakeIntegerSeqDecl() const
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 getAutoType(QualType DeducedType, AutoTypeKeyword Keyword, bool IsDependent, bool IsPack=false, ConceptDecl *TypeConstraintConcept=nullptr, ArrayRef< TemplateArgument > TypeConstraintArgs={}) const
C++11 deduced auto type.
QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT)
TypedefDecl * getObjCSelDecl() const
Retrieve the typedef corresponding to the predefined 'SEL' type in Objective-C.
CanQualType UnsignedShortAccumTy
Definition: ASTContext.h:1134
TypedefDecl * getObjCInstanceTypeDecl()
Retrieve the typedef declaration corresponding to the Objective-C "instancetype" type.
uint64_t getFieldOffset(const ValueDecl *FD) const
Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, ArrayRef< TemplateArgumentLoc > Args) const
void setTemplateOrSpecializationInfo(VarDecl *Inst, TemplateOrSpecializationInfo TSI)
bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto, ObjCProtocolDecl *rProto) const
ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the inheritance hierarchy of 'rProto...
bool hasSimilarType(QualType T1, QualType T2)
Determine if two types are similar, according to the C++ rules.
TypedefDecl * buildImplicitTypedef(QualType T, StringRef Name) const
Create a new implicit TU-level typedef declaration.
QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl, ObjCInterfaceDecl *PrevDecl=nullptr) const
getObjCInterfaceType - Return the unique reference to the type for the specified ObjC interface decl.
void adjustObjCTypeParamBoundType(const ObjCTypeParamDecl *Orig, ObjCTypeParamDecl *New) const
QualType getBlockPointerType(QualType T) const
Return the uniqued reference to the type for a block of the specified type.
TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg) const
Retrieve the "canonical" template argument.
QualType getAutoRRefDeductType() const
C++11 deduction pattern for 'auto &&' type.
TypedefDecl * getBuiltinMSVaListDecl() const
Retrieve the C type declaration corresponding to the predefined __builtin_ms_va_list type.
bool ObjCQualifiedIdTypesAreCompatible(const ObjCObjectPointerType *LHS, const ObjCObjectPointerType *RHS, bool ForCompare)
ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an ObjCQualifiedIDType.
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl.
QualType getMemberPointerType(QualType T, const Type *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
QualType getBuiltinVaListType() const
Retrieve the type of the __builtin_va_list type.
Definition: ASTContext.h:2172
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:664
comments::FullComment * cloneFullComment(comments::FullComment *FC, const Decl *D) const
Definition: ASTContext.cpp:560
TemplateName getCanonicalTemplateName(const TemplateName &Name) const
Retrieves the "canonical" template name that refers to a given template.
QualType getUnresolvedUsingType(const UnresolvedUsingTypenameDecl *Decl) 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.
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.
QualType getTemplateSpecializationType(TemplateName T, ArrayRef< TemplateArgument > Args, QualType Canon=QualType()) const
std::unique_ptr< MangleNumberingContext > createMangleNumberingContext() const
CanQualType SatAccumTy
Definition: ASTContext.h:1137
QualType getUnsignedPointerDiffType() const
Return the unique unsigned counterpart of "ptrdiff_t" integer type.
QualType getucontext_tType() const
Retrieve the C ucontext_t type.
Definition: ASTContext.h:2046
QualType getRecordType(const RecordDecl *Decl) const
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 getInjectedClassNameType(CXXRecordDecl *Decl, QualType TST) const
getInjectedClassNameType - Return the unique reference to the injected class name type for the specif...
QualType getVariableArrayType(QualType EltTy, Expr *NumElts, ArraySizeModifier ASM, unsigned IndexTypeQuals, SourceRange Brackets) const
Return a non-unique reference to the type for a variable array of the specified element type.
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like 'int()'.
CanQualType ShortAccumTy
Definition: ASTContext.h:1132
ASTMutationListener * getASTMutationListener() const
Retrieve a pointer to the AST mutation listener associated with this AST context, if any.
Definition: ASTContext.h:1242
unsigned NumImplicitCopyAssignmentOperatorsDeclared
The number of implicitly-declared copy assignment operators for which declarations were built.
Definition: ASTContext.h:3291
uint64_t getTargetNullPointerValue(QualType QT) const
Get target-dependent integer value for null pointer which is used for constant folding.
unsigned getTypeUnadjustedAlign(QualType T) const
Return the ABI-specified natural alignment of a (complete) type T, before alignment adjustments,...
Definition: ASTContext.h:2433
unsigned char getFixedPointIBits(QualType Ty) const
QualType getCorrespondingSignedFixedPointType(QualType Ty) const
CanQualType FloatTy
Definition: ASTContext.h:1131
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
QualType getPackExpansionType(QualType Pattern, std::optional< unsigned > NumExpansions, bool ExpectPackInType=true)
Form a pack expansion type with the given pattern.
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2628
unsigned NumImplicitDestructorsDeclared
The number of implicitly-declared destructors for which declarations were built.
Definition: ASTContext.h:3305
bool mergeExtParameterInfo(const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType, bool &CanUseFirst, bool &CanUseSecond, SmallVectorImpl< FunctionProtoType::ExtParameterInfo > &NewParamInfos)
This function merges the ExtParameterInfo lists of two functions.
bool ObjCQualifiedClassTypesAreCompatible(const ObjCObjectPointerType *LHS, const ObjCObjectPointerType *RHS)
ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and Class<pr1, ...>.
bool shouldExternalize(const Decl *D) const
Whether a C++ static variable or CUDA/HIP kernel should be externalized.
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2644
bool propertyTypesAreCompatible(QualType, QualType)
void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst, UsingShadowDecl *Pattern)
CanQualType DoubleTy
Definition: ASTContext.h:1131
TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS, bool TemplateKeyword, TemplateName Template) const
Retrieve the template name that represents a qualified template name such as std::vector.
QualType getDependentVectorType(QualType VectorType, Expr *SizeExpr, SourceLocation AttrLoc, VectorKind VecKind) const
Return the unique reference to the type for a dependently sized vector of the specified element type.
CanQualType SatLongAccumTy
Definition: ASTContext.h:1137
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.
QualType getFILEType() const
Retrieve the C FILE type.
Definition: ASTContext.h:2010
ArrayRef< Decl * > getModuleInitializers(Module *M)
Get the initializations to perform when importing a module, if any.
void getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT, std::string &S) const
Put the string version of the type qualifiers QT into S.
unsigned getPreferredTypeAlign(QualType T) const
Return the "preferred" alignment of the specified type T for the current target, in bits.
Definition: ASTContext.h:2485
void getInjectedTemplateArgs(const TemplateParameterList *Params, SmallVectorImpl< TemplateArgument > &Args)
Get a template argument list with one argument per template parameter in a template parameter list,...
std::string getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, bool Extended=false) const
Emit the encoded type for the method declaration Decl into S.
bool DeclMustBeEmitted(const Decl *D)
Determines if the decl can be CodeGen'ed or deserialized from PCH lazily, only when used; this is onl...
CanQualType LongDoubleTy
Definition: ASTContext.h:1131
CanQualType OMPArrayShapingTy
Definition: ASTContext.h:1160
ASTContext(LangOptions &LOpts, SourceManager &SM, IdentifierTable &idents, SelectorTable &sels, Builtin::Context &builtins, TranslationUnitKind TUKind)
Definition: ASTContext.cpp:872
QualType getReadPipeType(QualType T) const
Return a read_only pipe type for the specified type.
std::string getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, const Decl *Container) const
getObjCEncodingForPropertyDecl - Return the encoded type for this method declaration.
CanQualType Char16Ty
Definition: ASTContext.h:1126
unsigned getStaticLocalNumber(const VarDecl *VD) const
void addComment(const RawComment &RC)
Definition: ASTContext.cpp:328
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...
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod, bool IsBuiltin=false) const
Retrieves the default calling convention for the current target.
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.
QualType getMSGuidType() const
Retrieve the implicitly-predeclared 'struct _GUID' type.
Definition: ASTContext.h:2194
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...
const ASTRecordLayout & getASTObjCImplementationLayout(const ObjCImplementationDecl *D) const
Get or compute information about the layout of the specified Objective-C implementation.
CanQualType UnsignedLongFractTy
Definition: ASTContext.h:1136
QualType getEnumType(const EnumDecl *Decl) const
overridden_method_range overridden_methods(const CXXMethodDecl *Method) const
QualType getDependentBitIntType(bool Unsigned, Expr *BitsExpr) const
Return a dependent bit-precise integer type with the specified signedness and bit count.
void setObjCImplementation(ObjCInterfaceDecl *IFaceD, ObjCImplementationDecl *ImplD)
Set the implementation of ObjCInterfaceDecl.
StringRef getCUIDHash() const
bool isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const
Returns true if this is an inline-initialized static data member which is treated as a definition for...
bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT)
canAssignObjCInterfaces - Return true if the two interface types are compatible for assignment from R...
CanQualType VoidPtrTy
Definition: ASTContext.h:1146
QualType getReferenceQualifiedType(const Expr *e) const
getReferenceQualifiedType - Given an expr, will return the type for that expression,...
bool hasSameFunctionTypeIgnoringExceptionSpec(QualType T, QualType U) const
Determine whether two function types are the same, ignoring exception specifications in cases where t...
QualType getBlockDescriptorExtendedType() const
Gets the struct used to keep track of the extended descriptor for pointer to blocks.
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
CanQualType DependentTy
Definition: ASTContext.h:1147
IdentifierInfo * getMakeIntegerSeqName() const
Definition: ASTContext.h:1984
bool QIdProtocolsAdoptObjCObjectProtocols(QualType QT, ObjCInterfaceDecl *IDecl)
QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in QT's qualified-id protocol list adopt...
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...
IdentifierInfo * getTypePackElementName() const
Definition: ASTContext.h:1990
bool BlockRequiresCopying(QualType Ty, const VarDecl *D)
Returns true iff we need copy/dispose helpers for the given type.
CanQualType NullPtrTy
Definition: ASTContext.h:1146
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1637
CanQualType WideCharTy
Definition: ASTContext.h:1123
CanQualType OMPIteratorTy
Definition: ASTContext.h:1160
IdentifierTable & Idents
Definition: ASTContext.h:660
TemplateName getSubstTemplateTemplateParm(TemplateName replacement, Decl *AssociatedDecl, unsigned Index, std::optional< unsigned > PackIndex) const
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:662
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:797
TemplateArgument getInjectedTemplateArg(NamedDecl *ParamDecl)
QualType getFunctionTypeWithoutPtrSizes(QualType T)
Get a function type and produce the equivalent function type where pointer size address spaces in the...
llvm::iterator_range< overridden_cxx_method_iterator > overridden_method_range
Definition: ASTContext.h:1023
unsigned getMinGlobalAlignOfVar(uint64_t Size, const VarDecl *VD) const
Return the minimum alignement as specified by the target.
RawCommentList Comments
All comments in this translation unit.
Definition: ASTContext.h:827
bool isSameDefaultTemplateArgument(const NamedDecl *X, const NamedDecl *Y) const
Determine whether two default template arguments are similar enough that they may be used in declarat...
QualType applyObjCProtocolQualifiers(QualType type, ArrayRef< ObjCProtocolDecl * > protocols, bool &hasError, bool allowOnPointerType=false) const
Apply Objective-C protocol qualifiers to the given type.
QualType getMacroQualifiedType(QualType UnderlyingTy, const IdentifierInfo *MacroII) const
QualType removePtrSizeAddrSpace(QualType T) const
Remove the existing address space on the type if it is a pointer size address space and return the ty...
bool areLaxCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible RISC-V vector types as defined by -flax-vect...
CanQualType SatShortFractTy
Definition: ASTContext.h:1140
QualType getDecayedType(QualType T) const
Return the uniqued reference to the decayed version of the given type.
bool canBindObjCObjectType(QualType To, QualType From)
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...
Qualifiers::GC getObjCGCAttrKind(QualType Ty) const
Return one of the GCNone, Weak or Strong Objective-C garbage collection attributes.
CanQualType Ibm128Ty
Definition: ASTContext.h:1131
bool hasUniqueObjectRepresentations(QualType Ty, bool CheckIfTriviallyCopyable=true) const
Return true if the specified type has unique object representations according to (C++17 [meta....
bool typesAreBlockPointerCompatible(QualType, QualType)
CanQualType SatUnsignedAccumTy
Definition: ASTContext.h:1138
bool useAbbreviatedThunkName(GlobalDecl VirtualMethodDecl, StringRef MangledName)
const ASTRecordLayout & getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const
Get or compute information about the layout of the specified Objective-C interface.
void forEachMultiversionedFunctionVersion(const FunctionDecl *FD, llvm::function_ref< void(FunctionDecl *)> Pred) const
Visits all versions of a multiversioned function with the passed predicate.
void setInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst, UsingEnumDecl *Pattern)
Remember that the using enum decl Inst is an instantiation of the using enum decl Pattern of a class ...
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
QualType getSignatureParameterType(QualType T) const
Retrieve the parameter type as adjusted for use in the signature of a function, decaying array and fu...
CanQualType ArraySectionTy
Definition: ASTContext.h:1159
QualType getCanonicalTemplateSpecializationType(TemplateName T, ArrayRef< TemplateArgument > Args) const
CanQualType ObjCBuiltinIdTy
Definition: ASTContext.h:1151
overridden_cxx_method_iterator overridden_methods_end(const CXXMethodDecl *Method) const
VTableContextBase * getVTableContext()
int getFloatingTypeOrder(QualType LHS, QualType RHS) const
Compare the rank of the two specified floating point types, ignoring the domain of the type (i....
unsigned CountNonClassIvars(const ObjCInterfaceDecl *OI) const
ObjCPropertyImplDecl * getObjCPropertyImplDeclForPropertyDecl(const ObjCPropertyDecl *PD, const Decl *Container) const
bool isNearlyEmpty(const CXXRecordDecl *RD) const
QualType AutoDeductTy
Definition: ASTContext.h:1181
CanQualType BoolTy
Definition: ASTContext.h:1120
void cacheRawCommentForDecl(const Decl &OriginalD, const RawComment &Comment) const
Attaches Comment to OriginalD and to its redeclaration chain and removes the redeclaration chain from...
Definition: ASTContext.cpp:472
void attachCommentsToJustParsedDecls(ArrayRef< Decl * > Decls, const Preprocessor *PP)
Searches existing comments for doc comments that should be attached to Decls.
Definition: ASTContext.cpp:498
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.
FieldDecl * getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field)
void eraseDeclAttrs(const Decl *D)
Erase the attributes corresponding to the given declaration.
UsingEnumDecl * getInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst)
If the given using-enum decl Inst is an instantiation of another using-enum decl, return it.
RecordDecl * getCFConstantStringTagDecl() const
QualType getObjCSelType() const
Retrieve the type that corresponds to the predefined Objective-C 'SEL' type.
Definition: ASTContext.h:2127
QualType getDeducedTemplateSpecializationType(TemplateName Template, QualType DeducedType, bool IsDependent) const
C++17 deduced class template specialization type.
std::string getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const
Emit the encoded type for the function Decl into S.
QualType getTemplateTypeParmType(unsigned Depth, unsigned Index, bool ParameterPack, TemplateTypeParmDecl *ParmDecl=nullptr) const
Retrieve the template type parameter type for a template parameter or parameter pack with the given d...
CanQualType UnsignedFractTy
Definition: ASTContext.h:1136
QualType getjmp_bufType() const
Retrieve the C jmp_buf type.
Definition: ASTContext.h:2022
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
QualType mergeFunctionParameterTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false)
mergeFunctionParameterTypes - merge two types which appear as function parameter types
QualType getsigjmp_bufType() const
Retrieve the C sigjmp_buf type.
Definition: ASTContext.h:2034
void addOverriddenMethod(const CXXMethodDecl *Method, const CXXMethodDecl *Overridden)
Note that the given C++ Method overrides the given Overridden method.
CanQualType Float128Ty
Definition: ASTContext.h:1131
CanQualType ObjCBuiltinClassTy
Definition: ASTContext.h:1151
unsigned NumImplicitDefaultConstructorsDeclared
The number of implicitly-declared default constructors for which declarations were built.
Definition: ASTContext.h:3270
CanQualType UnresolvedTemplateTy
Definition: ASTContext.h:1147
OMPTraitInfo & getNewOMPTraitInfo()
Return a new OMPTraitInfo object owned by this context.
CanQualType UnsignedLongTy
Definition: ASTContext.h:1129
bool hasSameTemplateName(const TemplateName &X, const TemplateName &Y) const
Determine whether the given template names refer to the same template.
void DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, bool leafClass, SmallVectorImpl< const ObjCIvarDecl * > &Ivars) const
DeepCollectObjCIvars - This routine first collects all declared, but not synthesized,...
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,...
void addedLocalImportDecl(ImportDecl *Import)
Notify the AST context that a new import declaration has been parsed or implicitly created within thi...
CanQualType UnsignedLongAccumTy
Definition: ASTContext.h:1134
QualType AutoRRefDeductTy
Definition: ASTContext.h:1182
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
TypeInfo getTypeInfo(const Type *T) const
Get the size and alignment of the specified complete type in bits.
CanQualType ShortFractTy
Definition: ASTContext.h:1135
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.
TypeSourceInfo * getTemplateSpecializationTypeInfo(TemplateName T, SourceLocation TLoc, const TemplateArgumentListInfo &Args, QualType Canon=QualType()) const
QualType getSubstTemplateTypeParmPackType(Decl *AssociatedDecl, unsigned Index, bool Final, const TemplateArgument &ArgPack)
Retrieve a.
CanQualType BoundMemberTy
Definition: ASTContext.h:1147
CanQualType SatUnsignedShortFractTy
Definition: ASTContext.h:1141
CanQualType CharTy
Definition: ASTContext.h:1121
QualType removeAddrSpaceQualType(QualType T) const
Remove any existing address space on the type and returns the type with qualifiers intact (or that's ...
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:830
BlockVarCopyInit getBlockVarCopyInit(const VarDecl *VD) const
Get the copy initialization expression of the VarDecl VD, or nullptr if none exists.
unsigned NumImplicitMoveConstructorsDeclared
The number of implicitly-declared move constructors for which declarations were built.
Definition: ASTContext.h:3284
unsigned NumImplicitCopyConstructorsDeclared
The number of implicitly-declared copy constructors for which declarations were built.
Definition: ASTContext.h:3277
CanQualType IntTy
Definition: ASTContext.h:1128
llvm::DenseSet< const VarDecl * > CUDADeviceVarODRUsedByHost
Keep track of CUDA/HIP device-side variables ODR-used by host code.
Definition: ASTContext.h:1195
CanQualType PseudoObjectTy
Definition: ASTContext.h:1150
QualType getWebAssemblyExternrefType() const
Return a WebAssembly externref type.
void setTraversalScope(const std::vector< Decl * > &)
Definition: ASTContext.cpp:939
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.
void PrintStats() const
Definition: ASTContext.cpp:953
unsigned getAlignOfGlobalVar(QualType T, const VarDecl *VD) const
Return the alignment in bits that should be given to a global variable with type T.
TypeInfoChars getTypeInfoDataSizeInChars(QualType T) const
MangleNumberingContext & getManglingNumberContext(const DeclContext *DC)
Retrieve the context for computing mangling numbers in the given DeclContext.
comments::FullComment * getLocalCommentForDeclUncached(const Decl *D) const
Return parsed documentation comment attached to a given declaration.
Definition: ASTContext.cpp:575
unsigned NumImplicitDestructors
The number of implicitly-declared destructors.
Definition: ASTContext.h:3301
CanQualType Float16Ty
Definition: ASTContext.h:1145
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2210
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, QualType NamedType, TagDecl *OwnedTagDecl=nullptr) const
bool isAlignmentRequired(const Type *T) const
Determine if the alignment the type has was required using an alignment attribute.
TagDecl * MSGuidTagDecl
Definition: ASTContext.h:1189
bool areComparableObjCPointerTypes(QualType LHS, QualType RHS)
MangleContext * createDeviceMangleContext(const TargetInfo &T)
Creates a device mangle context to correctly mangle lambdas in a mixed architecture compile by settin...
CharUnits getExnObjectAlignment() const
Return the alignment (in bytes) of the thrown exception object.
CanQualType SignedCharTy
Definition: ASTContext.h:1128
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
ASTMutationListener * Listener
Definition: ASTContext.h:666
CanQualType ObjCBuiltinBoolTy
Definition: ASTContext.h:1152
TypeInfoChars getTypeInfoInChars(const Type *T) const
QualType getObjCObjectType(QualType Base, ObjCProtocolDecl *const *Protocols, unsigned NumProtocols) const
Legacy interface: cannot provide type arguments or __kindof.
TemplateParamObjectDecl * getTemplateParamObjectDecl(QualType T, const APValue &V) const
Return the template parameter object of the given type with the given value.
CanQualType OverloadTy
Definition: ASTContext.h:1147
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.
CanQualType OCLClkEventTy
Definition: ASTContext.h:1156
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:713
ArrayRef< Module * > getModulesWithMergedDefinition(const NamedDecl *Def)
Get the additional modules in which the definition Def has been merged.
llvm::FixedPointSemantics getFixedPointSemantics(QualType Ty) const
QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts, ArraySizeModifier ASM, unsigned IndexTypeQuals, SourceRange Brackets) const
Return a non-unique reference to the type for a dependently-sized array of the specified element type...
uint64_t lookupFieldBitOffset(const ObjCInterfaceDecl *OID, const ObjCImplementationDecl *ID, const ObjCIvarDecl *Ivar) const
Get the offset of an ObjCIvarDecl in bits.
CanQualType SatUnsignedShortAccumTy
Definition: ASTContext.h:1138
QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false, bool BlockReturnType=false, bool IsConditionalOperator=false)
const RawComment * getRawCommentForAnyRedecl(const Decl *D, const Decl **OriginalDecl=nullptr) const
Return the documentation comment attached to a given declaration.
Definition: ASTContext.cpp:404
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.
static bool isObjCNSObjectType(QualType Ty)
Return true if this is an NSObject object with its NSObject attribute set.
Definition: ASTContext.h:2374
GVALinkage GetGVALinkageForVariable(const VarDecl *VD) const
UsingShadowDecl * getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst)
QualType getObjCIdType() const
Represents the Objective-CC id type.
Definition: ASTContext.h:2117
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".
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2675
QualType getCorrespondingUnsaturatedType(QualType Ty) const
comments::FullComment * getCommentForDecl(const Decl *D, const Preprocessor *PP) const
Return parsed documentation comment attached to a given declaration.
Definition: ASTContext.cpp:580
FunctionProtoType::ExceptionSpecInfo mergeExceptionSpecs(FunctionProtoType::ExceptionSpecInfo ESI1, FunctionProtoType::ExceptionSpecInfo ESI2, SmallVectorImpl< QualType > &ExceptionTypeStorage, bool AcceptDependent)
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.
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.
const CXXRecordDecl * baseForVTableAuthentication(const CXXRecordDecl *ThisClass)
Resolve the root record to be used to derive the vtable pointer authentication policy for the specifi...
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2394
CanQualType UnsignedInt128Ty
Definition: ASTContext.h:1130
CanQualType BuiltinFnTy
Definition: ASTContext.h:1149
ObjCInterfaceDecl * getObjCProtocolDecl() const
Retrieve the Objective-C class declaration corresponding to the predefined Protocol class.
unsigned NumImplicitDefaultConstructors
The number of implicitly-declared default constructors.
Definition: ASTContext.h:3266
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
unsigned NumImplicitMoveAssignmentOperatorsDeclared
The number of implicitly-declared move assignment operators for which declarations were built.
Definition: ASTContext.h:3298
void setManglingNumber(const NamedDecl *ND, unsigned Number)
llvm::DenseMap< const Decl *, const RawComment * > DeclRawComments
Mapping from declaration to directly attached comment.
Definition: ASTContext.h:836
CanQualType OCLSamplerTy
Definition: ASTContext.h:1156
TypedefDecl * getBuiltinVaListDecl() const
Retrieve the C type declaration corresponding to the predefined __builtin_va_list type.
CanQualType VoidTy
Definition: ASTContext.h:1119
CanQualType UnsignedCharTy
Definition: ASTContext.h:1129
CanQualType UnsignedShortFractTy
Definition: ASTContext.h:1136
BuiltinTemplateDecl * buildBuiltinTemplateDecl(BuiltinTemplateKind BTK, const IdentifierInfo *II) const
void * Allocate(size_t Size, unsigned Align=8) const
Definition: ASTContext.h:734
bool canBuiltinBeRedeclared(const FunctionDecl *) const
Return whether a declaration to a builtin is allowed to be overloaded/redeclared.
CanQualType UnsignedIntTy
Definition: ASTContext.h:1129
TemplateName getDependentTemplateName(NestedNameSpecifier *NNS, const IdentifierInfo *Name) const
Retrieve the template name that represents a dependent template name such as MetaFun::template apply.
unsigned NumImplicitMoveConstructors
The number of implicitly-declared move constructors.
Definition: ASTContext.h:3280
QualType getObjCTypeParamType(const ObjCTypeParamDecl *Decl, ArrayRef< ObjCProtocolDecl * > protocols) const
QualType getVolatileType(QualType T) const
Return the uniqued reference to the type for a volatile qualified type.
Definition: ASTContext.h:1334
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.
TypeSourceInfo * CreateTypeSourceInfo(QualType T, unsigned Size=0) const
Allocate an uninitialized TypeSourceInfo.
QualType getExceptionObjectType(QualType T) const
CanQualType UnknownAnyTy
Definition: ASTContext.h:1148
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 ...
DeclaratorDecl * getDeclaratorForUnnamedTagDecl(const TagDecl *TD)
bool ObjCObjectAdoptsQTypeProtocols(QualType QT, ObjCInterfaceDecl *Decl)
ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's protocol list adopt all protocols in Q...
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1130
QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error, unsigned *IntegerConstantArgs=nullptr) const
Return the type for the specified builtin.
QualType getCommonSugaredType(QualType X, QualType Y, bool Unqualified=false)
CanQualType OCLReserveIDTy
Definition: ASTContext.h:1157
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...
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
overridden_cxx_method_iterator overridden_methods_begin(const CXXMethodDecl *Method) const
CanQualType UnsignedShortTy
Definition: ASTContext.h:1129
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...
bool AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1615
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, QualType Canon=QualType()) const
bool canAssignObjCInterfacesInBlockPointer(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT, bool BlockReturnType)
canAssignObjCInterfacesInBlockPointer - This routine is specifically written for providing type-safet...
CanQualType SatUnsignedLongFractTy
Definition: ASTContext.h:1142
const CXXConstructorDecl * getCopyConstructorForExceptionObject(CXXRecordDecl *RD)
QualType getDependentAddressSpaceType(QualType PointeeType, Expr *AddrSpaceExpr, SourceLocation AttrLoc) const
QualType getPackIndexingType(QualType Pattern, Expr *IndexExpr, bool FullySubstituted=false, ArrayRef< QualType > Expansions={}, int Index=-1) const
RawComment * getRawCommentForDeclNoCache(const Decl *D) const
Return the documentation comment attached to a given declaration, without looking into cache.
Definition: ASTContext.cpp:295
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
const VariableArrayType * getAsVariableArrayType(QualType T) const
Definition: ASTContext.h:2828
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.
Definition: ASTContext.cpp:949
const ObjCInterfaceDecl * getObjContainingInterface(const NamedDecl *ND) const
Returns the Objective-C interface that ND belongs to if it is an Objective-C method/property/ivar etc...
CanQualType ShortTy
Definition: ASTContext.h:1128
StringLiteral * getPredefinedStringLiteralFromCache(StringRef Key) const
Return a string representing the human readable name for the specified function declaration or file n...
bool UnwrapSimilarTypes(QualType &T1, QualType &T2, bool AllowPiMismatch=true)
Attempt to unwrap two types that may be similar (C++ [conv.qual]).
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 areCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given types are an SVE builtin and a VectorType that is a fixed-length representat...
bool hasDirectOwnershipQualifier(QualType Ty) const
Return true if the type has been explicitly qualified with ObjC ownership.
CanQualType FractTy
Definition: ASTContext.h:1135
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)
DiagnosticsEngine & getDiagnostics() const
QualType getAdjustedParameterType(QualType T) const
Perform adjustment on the parameter type of a function.
void ResetObjCLayout(const ObjCContainerDecl *CD)
CanQualType LongAccumTy
Definition: ASTContext.h:1133
interp::Context & getInterpContext()
Returns the clang bytecode interpreter context.
Definition: ASTContext.cpp:846
CanQualType Char32Ty
Definition: ASTContext.h:1127
UnnamedGlobalConstantDecl * getUnnamedGlobalConstantDecl(QualType Ty, const APValue &Value) const
Return a declaration for a uniquified anonymous global constant corresponding to a given APValue.
CanQualType SatFractTy
Definition: ASTContext.h:1140
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size.
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
CanQualType SatLongFractTy
Definition: ASTContext.h:1140
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:779
void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl)
CanQualType OCLQueueTy
Definition: ASTContext.h:1157
CanQualType LongFractTy
Definition: ASTContext.h:1135
CanQualType SatShortAccumTy
Definition: ASTContext.h:1137
QualType getAutoDeductType() const
C++11 deduction pattern for 'auto' type.
CanQualType BFloat16Ty
Definition: ASTContext.h:1144
unsigned NumImplicitCopyConstructors
The number of implicitly-declared copy constructors.
Definition: ASTContext.h:3273
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
CanQualType IncompleteMatrixIdxTy
Definition: ASTContext.h:1158
void getFunctionFeatureMap(llvm::StringMap< bool > &FeatureMap, const FunctionDecl *) const
CanQualType getNSIntegerType() const
QualType getCorrespondingUnsignedType(QualType T) const
void setBlockVarCopyInit(const VarDecl *VD, Expr *CopyExpr, bool CanThrow)
Set the copy initialization expression of a block var decl.
TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin, UnresolvedSetIterator End) const
Retrieve the template name that corresponds to a non-empty lookup.
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
TemplateName getSubstTemplateTemplateParmPack(const TemplateArgument &ArgPack, Decl *AssociatedDecl, unsigned Index, bool Final) const
TargetCXXABI::Kind getCXXABIKind() const
Return the C++ ABI kind that should be used.
Definition: ASTContext.cpp:820
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any.
Definition: ASTContext.h:1227
uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const
Return number of constant array elements.
BuiltinTemplateDecl * getTypePackElementDecl() const
CanQualType SatUnsignedLongAccumTy
Definition: ASTContext.h:1139
QualType getUnconstrainedType(QualType T) const
Remove any type constraints from a template parameter type, for equivalence comparison of template pa...
CanQualType LongLongTy
Definition: ASTContext.h:1128
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:852
uint64_t getArrayInitLoopExprElementCount(const ArrayInitLoopExpr *AILE) const
Return number of elements initialized in an ArrayInitLoopExpr.
void deduplicateMergedDefinitonsFor(NamedDecl *ND)
Clean up the merged definition list.
unsigned getTargetAddressSpace(LangAS AS) const
QualType getWideCharType() const
Return the type of wide characters.
Definition: ASTContext.h:1847
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...
void addTranslationUnitDecl()
Definition: ASTContext.h:1104
CanQualType WCharTy
Definition: ASTContext.h:1122
void getObjCEncodingForPropertyType(QualType T, std::string &S) const
Emit the Objective-C property type encoding for the given type T into S.
unsigned NumImplicitCopyAssignmentOperators
The number of implicitly-declared copy assignment operators.
Definition: ASTContext.h:3287
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:843
CanQualType getSignedSizeType() const
Return the unique signed counterpart of the integer type corresponding to size_t.
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.
NestedNameSpecifier * getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const
Retrieves the "canonical" nested name specifier for a given nested name specifier.
QualType getTypedefType(const TypedefNameDecl *Decl, QualType Underlying=QualType()) const
Return the unique reference to the type for the specified typedef-name decl.
InlineVariableDefinitionKind getInlineVariableDefinitionKind(const VarDecl *VD) const
Determine whether a definition of this inline variable should be treated as a weak or strong definiti...
CanQualType getUIntMaxType() const
Return the unique type for "uintmax_t" (C99 7.18.1.5), defined in <stdint.h>.
QualType getSubstTemplateTypeParmType(QualType Replacement, Decl *AssociatedDecl, unsigned Index, std::optional< unsigned > PackIndex) const
Retrieve a substitution-result type.
uint16_t getPointerAuthVTablePointerDiscriminator(const CXXRecordDecl *RD)
Return the "other" discriminator used for the pointer auth schema used for vtable pointers in instanc...
CharUnits getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const
Loading virtual member pointers using the virtual inheritance model always results in an adjustment u...
LangAS getLangASForBuiltinAddressSpace(unsigned AS) const
bool hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U)
Determine whether two function types are the same, ignoring pointer sizes in the return type and para...
unsigned char getFixedPointScale(QualType Ty) const
QualType getIncompleteArrayType(QualType EltTy, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return a unique reference to the type for an incomplete array of the specified element type.
QualType getDependentSizedExtVectorType(QualType VectorType, Expr *SizeExpr, SourceLocation AttrLoc) const
QualType DecodeTypeStr(const char *&Str, const ASTContext &Context, ASTContext::GetBuiltinTypeError &Error, bool &RequireICE, bool AllowTypeModifiers) const
TemplateName getAssumedTemplateName(DeclarationName Name) const
Retrieve a template name representing an unqualified-id that has been assumed to name a template for ...
@ GE_None
No error.
Definition: ASTContext.h:2296
@ GE_Missing_stdio
Missing a type from <stdio.h>
Definition: ASTContext.h:2302
@ GE_Missing_type
Missing a type.
Definition: ASTContext.h:2299
@ GE_Missing_ucontext
Missing a type from <ucontext.h>
Definition: ASTContext.h:2308
@ GE_Missing_setjmp
Missing a type from <setjmp.h>
Definition: ASTContext.h:2305
QualType adjustStringLiteralBaseType(QualType StrLTy) const
uint16_t getPointerAuthTypeDiscriminator(QualType T)
Return the "other" type-specific discriminator for the given type.
QualType getTypeOfExprType(Expr *E, TypeOfKind Kind) const
C23 feature and GCC extension.
CanQualType Char8Ty
Definition: ASTContext.h:1125
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.
ObjCImplementationDecl * getObjCImplementation(ObjCInterfaceDecl *D)
Get the implementation of the ObjCInterfaceDecl D, or nullptr if none exists.
CanQualType HalfTy
Definition: ASTContext.h:1143
CanQualType UnsignedAccumTy
Definition: ASTContext.h:1134
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.
QualType getVariableArrayDecayedType(QualType Ty) const
Returns a vla type where known sizes are replaced with [*].
bool isInSameModule(const Module *M1, const Module *M2)
If the two module M1 and M2 are in the same module.
void setCFConstantStringType(QualType T)
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...
CanQualType OCLEventTy
Definition: ASTContext.h:1156
void AddDeallocation(void(*Callback)(void *), void *Data) const
Add a deallocation callback that will be invoked when the ASTContext is destroyed.
Definition: ASTContext.cpp:944
AttrVec & getDeclAttrs(const Decl *D)
Retrieve the attributes for the given declaration.
CXXMethodVector::const_iterator overridden_cxx_method_iterator
Definition: ASTContext.h:1013
RawComment * getRawCommentForDeclNoCacheImpl(const Decl *D, const SourceLocation RepresentativeLocForDecl, const std::map< unsigned, RawComment * > &CommentsInFile) const
Definition: ASTContext.cpp:217
unsigned getTypeAlign(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in bits.
Definition: ASTContext.h:2425
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
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Definition: ASTContext.h:2398
QualType getBitIntType(bool Unsigned, unsigned NumBits) const
Return a bit-precise integer type with the specified signedness and bit count.
unsigned NumImplicitMoveAssignmentOperators
The number of implicitly-declared move assignment operators.
Definition: ASTContext.h:3294
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
virtual void AddedStaticLocalNumbers(const Decl *D, unsigned Number)
An static local number was added to a Decl.
virtual void RedefinedHiddenDefinition(const NamedDecl *D, Module *M)
A definition has been made visible by being redefined locally.
virtual void AddedManglingNumber(const Decl *D, unsigned Number)
An mangling number was added to a Decl.
virtual void DeducedReturnType(const FunctionDecl *FD, QualType ReturnType)
A function's return type has been deduced.
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
Definition: RecordLayout.h:38
CharUnits getAlignment() const
getAlignment - Get the record alignment in characters.
Definition: RecordLayout.h:182
const CXXRecordDecl * getBaseSharingVBPtr() const
Definition: RecordLayout.h:329
CharUnits getSize() const
getSize - Get the record size in characters.
Definition: RecordLayout.h:193
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
Definition: RecordLayout.h:200
CharUnits getDataSize() const
getDataSize() - Get the record data size, which is the record size without tail padding,...
Definition: RecordLayout.h:206
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
Definition: RecordLayout.h:249
CharUnits getVBaseClassOffset(const CXXRecordDecl *VBase) const
getVBaseClassOffset - Get the offset, in chars, for the given base class.
Definition: RecordLayout.h:259
CharUnits getNonVirtualSize() const
getNonVirtualSize - Get the non-virtual size (in chars) of an object, which is the size of the object...
Definition: RecordLayout.h:210
CharUnits getUnadjustedAlignment() const
getUnadjustedAlignment - Get the record alignment in characters, before alignment adjustement.
Definition: RecordLayout.h:190
Represents a type which was implicitly adjusted by the semantic engine for arbitrary reasons.
Definition: Type.h:3351
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3370
Represents a loop initializing the elements of an array.
Definition: Expr.h:5703
llvm::APInt getArraySize() const
Definition: Expr.h:5725
Expr * getSubExpr() const
Get the initializer to use for each array element.
Definition: Expr.h:5723
Represents a constant array type that does not decay to a pointer when used as a function parameter.
Definition: Type.h:3741
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3571
ArraySizeModifier getSizeModifier() const
Definition: Type.h:3585
Qualifiers getIndexTypeQualifiers() const
Definition: Type.h:3589
QualType getElementType() const
Definition: Type.h:3583
unsigned getIndexTypeCVRQualifiers() const
Definition: Type.h:3593
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:6629
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition: Type.h:7585
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:7590
Attr - This represents one attribute.
Definition: Attr.h:42
An attributed type is a type to which a type attribute has been applied.
Definition: Type.h:6025
static Kind getNullabilityAttrKind(NullabilityKind kind)
Retrieve the attribute kind corresponding to the given nullability kind.
Definition: Type.h:6080
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:6108
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:6380
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.cpp:5103
bool isConstrained() const
Definition: Type.h:6399
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:6143
A fixed int type of a specified bitwidth.
Definition: Type.h:7638
void Profile(llvm::FoldingSetNodeID &ID) const
Definition: Type.h:7655
unsigned getNumBits() const
Definition: Type.h:7650
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4471
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:6365
Pointer to a block type.
Definition: Type.h:3402
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3419
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: Type.h:3028
Kind getKind() const
Definition: Type.h:3076
StringRef getName(const PrintingPolicy &Policy) const
Definition: Type.cpp:3283
Holds information about both target-independent and target-specific builtins, allowing easy queries b...
Definition: Builtins.h:85
const char * getTypeString(unsigned ID) const
Get the type descriptor string for the specified builtin.
Definition: Builtins.h:106
bool hasCustomTypechecking(unsigned ID) const
Determines whether this builtin has custom typechecking.
Definition: Builtins.h:196
bool canBeRedeclared(unsigned ID) const
Returns true if this is a builtin that can be redeclared.
Definition: Builtins.cpp:242
bool isNoReturn(unsigned ID) const
Return true if we know this builtin never returns.
Definition: Builtins.h:132
bool isNoThrow(unsigned ID) const
Return true if we know this builtin never throws an exception.
Definition: Builtins.h:127
Implements C++ ABI-specific semantic analysis functions.
Definition: CXXABI.h:29
virtual ~CXXABI()
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2539
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2064
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:2160
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition: DeclCXX.h:1219
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr, bool DelayTypeCreation=false)
Definition: DeclCXX.cpp:132
bool isDynamicClass() const
Definition: DeclCXX.h:586
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition: DeclCXX.h:1191
SplitQualType split() const
static CanQual< Type > CreateUnsafe(QualType Other)
Builds a canonical type from a QualType.
QualType withConst() const
Retrieves a version of this type with const applied.
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
bool isNull() const
Definition: CanonicalType.h:97
Qualifiers getQualifiers() const
Retrieve all qualifiers.
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
Definition: CanonicalType.h:83
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
bool isPositive() const
isPositive - Test whether the quantity is greater than zero.
Definition: CharUnits.h:128
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition: CharUnits.h:122
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:185
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition: CharUnits.h:63
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition: CharUnits.h:53
Declaration of a class template.
llvm::PointerUnion< ClassTemplateDecl *, ClassTemplatePartialSpecializationDecl * > getSpecializedTemplateOrPartial() const
Retrieve the class template or class template partial specialization which was specialized by this.
Complex values, per C99 6.2.5p11.
Definition: Type.h:3139
QualType getElementType() const
Definition: Type.h:3149
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3154
Declaration of a C++20 concept.
ConceptDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
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: Type.h:3609
const Expr * getSizeExpr() const
Return a pointer to the size expression.
Definition: Type.h:3705
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition: Type.h:3665
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition: Type.h:3724
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition: Type.h:3685
Represents a concrete matrix type with constant number of rows and columns.
Definition: Type.h:4224
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition: Type.h:4245
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:4262
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition: Type.h:4242
static constexpr bool isDimensionValid(size_t NumElements)
Returns true if NumElements is a valid matrix dimension.
Definition: Type.h:4253
Represents a sugar type with __counted_by or __sized_by annotations, including their _or_null variant...
Definition: Type.h:3300
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3336
Represents a pointer type decayed from an array or function type.
Definition: Type.h:3385
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1436
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2090
bool isFileContext() const
Definition: DeclBase.h:2161
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1333
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition: DeclBase.h:2106
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1852
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1988
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1766
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1265
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition: DeclBase.h:1051
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:317
T * getAttr() const
Definition: DeclBase.h:580
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:523
void addAttr(Attr *A)
Definition: DeclBase.cpp:1013
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:600
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl,...
Definition: DeclBase.cpp:537
static Decl * castFromDeclContext(const DeclContext *)
Definition: DeclBase.cpp:1041
bool isCanonicalDecl() const
Whether this particular Decl is a canonical one.
Definition: DeclBase.h:974
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:249
ObjCDeclQualifier
ObjCDeclQualifier - 'Qualifiers' written next to the return and parameter types in method declaration...
Definition: DeclBase.h:198
@ OBJC_TQ_Byref
Definition: DeclBase.h:204
@ OBJC_TQ_Oneway
Definition: DeclBase.h:205
@ OBJC_TQ_Bycopy
Definition: DeclBase.h:203
@ OBJC_TQ_None
Definition: DeclBase.h:199
@ OBJC_TQ_Inout
Definition: DeclBase.h:201
bool isInvalidDecl() const
Definition: DeclBase.h:595
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:566
SourceLocation getLocation() const
Definition: DeclBase.h:446
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack.
Definition: DeclBase.cpp:232
void setImplicit(bool I=true)
Definition: DeclBase.h:601
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: DeclBase.h:1039
DeclContext * getDeclContext()
Definition: DeclBase.h:455
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclBase.h:438
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition: DeclBase.cpp:358
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:908
bool hasAttr() const
Definition: DeclBase.h:584
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:968
Kind getKind() const
Definition: DeclBase.h:449
DeclarationNameLoc - Additional source/type location info for a declaration name.
static DeclarationNameLoc makeCXXOperatorNameLoc(SourceLocation BeginLoc, SourceLocation EndLoc)
Construct location information for a non-literal C++ operator.
DeclarationName getIdentifier(const IdentifierInfo *ID)
Create a declaration name that is a simple identifier.
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
The name of a declaration.
static int compare(DeclarationName LHS, DeclarationName RHS)
Represents a ValueDecl that came out of a declarator.
Definition: Decl.h:731
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:760
Represents the type decltype(expr) (C++11).
Definition: Type.h:5779
Represents a C++17 deduced template specialization type.
Definition: Type.h:6428
void Profile(llvm::FoldingSetNodeID &ID) const
Definition: Type.h:6449
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
Definition: Type.h:6346
Represents an extended address space qualifier where the input address space value is dependent.
Definition: Type.h:3912
Expr * getAddrSpaceExpr() const
Definition: Type.h:3923
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:3934
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:7683
Internal representation of canonical, dependent decltype(expr) types.
Definition: Type.h:5807
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:5811
Represents a qualified type name for which the type name is dependent.
Definition: Type.h:6848
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:6880
Represents an array type in C++ whose size is a value-dependent expression.
Definition: Type.h:3854
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:3891
Expr * getSizeExpr() const
Definition: Type.h:3874
Represents an extended vector type where either the type or size is dependent.
Definition: Type.h:3952
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:3977
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition: Type.h:4283
Expr * getRowExpr() const
Definition: Type.h:4295
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:4303
Represents a dependent template name that cannot be resolved prior to template instantiation.
Definition: TemplateName.h:491
OverloadedOperatorKind getOperator() const
Return the overloaded operator to which this template name refers.
Definition: TemplateName.h:563
bool isIdentifier() const
Determine whether this template name refers to an identifier.
Definition: TemplateName.h:550
const IdentifierInfo * getIdentifier() const
Returns the identifier to which this template name refers.
Definition: TemplateName.h:553
void Profile(llvm::FoldingSetNodeID &ID)
Definition: TemplateName.h:569
Represents a template specialization type whose template cannot be resolved, e.g.
Definition: Type.h:6900
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:6927
Internal representation of canonical, dependent typeof(expr) types.
Definition: Type.h:5736
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:5741
Internal representation of canonical, dependent __underlying_type(type) types.
Definition: Type.h:5930
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:5935
Represents a vector type where either the type or size is dependent.
Definition: Type.h:4078
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:4103
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:192
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1547
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
Definition: Diagnostic.h:873
Wrap a function effect's condition expression in another struct so that FunctionProtoType's TrailingO...
Definition: Type.h:4808
Represents a type that was referred to using an elaborated type keyword, e.g., struct S,...
Definition: Type.h:6767
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:6820
Represents an enum.
Definition: Decl.h:3844
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition: Decl.h:4049
bool isComplete() const
Returns true if this can be considered a complete type.
Definition: Decl.h:4063
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition: Decl.h:4004
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition: Decl.cpp:4937
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:5996
EnumDecl * getDecl() const
Definition: Type.h:6003
This represents one expression.
Definition: Expr.h:110
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:3075
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition: Expr.h:175
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:437
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:192
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition: Expr.cpp:4102
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition: Expr.h:826
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on.
Definition: Expr.h:221
bool isIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr) const
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3050
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:3941
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
QualType getType() const
Definition: Expr.h:142
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition: Expr.h:427
We can encode up to four bits in the low bits of a type pointer, but there are many more type qualifi...
Definition: Type.h:1713
void Profile(llvm::FoldingSetNodeID &ID) const
Definition: Type.h:1760
ExtVectorType - Extended vector type.
Definition: Type.h:4118
Declaration context for names declared as extern "C" in C++.
Definition: Decl.h:222
static ExternCContextDecl * Create(const ASTContext &C, TranslationUnitDecl *TU)
Definition: Decl.cpp:5331
Abstract interface for external sources of AST nodes.
virtual ExtKind hasExternalDefinitions(const Decl *D)
virtual void ReadComments()
Loads comment ranges.
virtual void CompleteRedeclChain(const Decl *D)
Gives the external AST source an opportunity to complete the redeclaration chain for a declaration.
virtual void PrintStats()
Print any statistics that have been gathered regarding the external AST source.
Represents a member of a struct/union/class.
Definition: Decl.h:3030
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:3121
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition: Decl.cpp:4630
unsigned getBitWidthValue(const ASTContext &Ctx) const
Computes the bit width of this field, if this is a bit field.
Definition: Decl.cpp:4578
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3247
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:4531
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:1932
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition: Decl.h:2562
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:3618
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2793
bool isMSExternInline() const
The combination of the extern and inline keywords under MSVC forces the function to be required.
Definition: Decl.cpp:3743
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:4252
bool isUserProvided() const
True if this method is user-declared and was not deleted or defaulted on its first declaration.
Definition: Decl.h:2335
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition: Decl.cpp:4000
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:3913
static FunctionEffectSet getIntersection(FunctionEffectsRef LHS, FunctionEffectsRef RHS)
Definition: Type.cpp:5251
static FunctionEffectSet getUnion(FunctionEffectsRef LHS, FunctionEffectsRef RHS, Conflicts &Errs)
Definition: Type.cpp:5289
Represents an abstract function effect, using just an enumeration describing its kind.
Definition: Type.h:4708
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition: Type.h:4887
size_t size() const
Definition: Type.h:4918
ArrayRef< EffectConditionExpr > conditions() const
Definition: Type.h:4921
bool empty() const
Definition: Type.h:4917
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition: Type.h:4673
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:4689
Represents a prototype with parameter type info, e.g.
Definition: Type.h:5007
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition: Type.h:5473
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition: Type.h:5287
unsigned getNumParams() const
Definition: Type.h:5260
QualType getParamType(unsigned i) const
Definition: Type.h:5262
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition: Type.cpp:3822
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition: Type.h:5293
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:5384
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:5271
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:5267
ArrayRef< ExtParameterInfo > getExtParameterInfos() const
Definition: Type.h:5449
bool hasExtParameterInfos() const
Is there any interesting extra information for any of the parameters of this function type?
Definition: Type.h:5445
Declaration of a template function.
Definition: DeclTemplate.h:957
A class which abstracts out some details necessary for making a call.
Definition: Type.h:4424
CallingConv getCC() const
Definition: Type.h:4486
bool getNoCfCheck() const
Definition: Type.h:4476
unsigned getRegParm() const
Definition: Type.h:4479
bool getNoCallerSavedRegs() const
Definition: Type.h:4475
ExtInfo withNoReturn(bool noReturn) const
Definition: Type.h:4498
bool getHasRegParm() const
Definition: Type.h:4477
bool getNoReturn() const
Definition: Type.h:4472
bool getProducesResult() const
Definition: Type.h:4473
Interesting information about a specific parameter that can't simply be reflected in parameter's type...
Definition: Type.h:4339
ExtParameterInfo withIsNoEscape(bool NoEscape) const
Definition: Type.h:4379
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4313
ExtInfo getExtInfo() const
Definition: Type.h:4647
QualType getReturnType() const
Definition: Type.h:4635
GlobalDecl - represents a global declaration.
Definition: GlobalDecl.h:56
unsigned getMultiVersionIndex() const
Definition: GlobalDecl.h:122
CXXDtorType getDtorType() const
Definition: GlobalDecl.h:110
const Decl * getDecl() const
Definition: GlobalDecl.h:103
One of these records is kept for each identifier that is lexed.
unsigned getLength() const
Efficiently return the length of this identifier info.
StringRef getName() const
Return the actual identifier string.
Implements an efficient mapping from strings to IdentifierInfo nodes.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
Describes a module import declaration, which makes the contents of the named module visible in the cu...
Definition: Decl.h:4783
Represents a C array with an unspecified size.
Definition: Type.h:3756
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3773
The injected class name of a C++ class template or class template partial specialization.
Definition: Type.h:6617
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: Type.h:3477
@ Swift
Interoperability with the latest known version of the Swift runtime.
@ Swift4_2
Interoperability with the Swift 4.2 runtime.
@ Swift4_1
Interoperability with the Swift 4.1 runtime.
@ Integer
Permit vector bitcasts between integer vectors with different numbers of elements but the same total ...
@ All
Permit vector bitcasts between all vectors with the same total bit-width.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:476
std::optional< TargetCXXABI::Kind > CXXABI
C++ ABI to compile with, if specified by the frontend through -fc++-abi=.
Definition: LangOptions.h:564
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:511
CoreFoundationABI CFRuntime
Definition: LangOptions.h:513
CommentOptions CommentOpts
Options for parsing comments.
Definition: LangOptions.h:540
std::string CUID
The user provided compilation unit ID, if non-empty.
Definition: LangOptions.h:560
A global _GUID constant.
Definition: DeclCXX.h:4293
static void Profile(llvm::FoldingSetNodeID &ID, Parts P)
Definition: DeclCXX.h:4330
Sugar type that represents a type that was qualified by a qualifier written as a macro invocation.
Definition: Type.h:5670
MangleContext - Context for tracking state which persists across multiple calls to the C++ name mangl...
Definition: Mangle.h:45
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: Type.h:4202
static bool isValidElementType(QualType T)
Valid elements types are the following:
Definition: Type.h:4209
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3513
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3549
QualType getPointeeType() const
Definition: Type.h:3529
const Type * getClass() const
Definition: Type.h:3543
Provides information a specialization of a member of a class template, which may be a member function...
Definition: DeclTemplate.h:615
static MicrosoftMangleContext * create(ASTContext &Context, DiagnosticsEngine &Diags, bool IsAux=false)
Describes a module or submodule.
Definition: Module.h:105
bool isNamedModule() const
Does this Module is a named module of a standard named module?
Definition: Module.h:185
This represents a decl that may have a name.
Definition: Decl.h:249
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:270
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:315
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:292
bool isExternallyVisible() const
Definition: Decl.h:408
NamespaceDecl * getNamespace()
Retrieve the namespace declaration aliased by this directive.
Definition: DeclCXX.h:3196
Represent a C++ namespace.
Definition: Decl.h:547
static NamespaceDecl * Create(ASTContext &C, DeclContext *DC, bool Inline, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, NamespaceDecl *PrevDecl, bool Nested)
Definition: DeclCXX.cpp:3013
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
bool isDependent() const
Whether this nested name specifier refers to a dependent type or not.
SpecifierKind getKind() const
Determine what kind of nested name specifier is stored.
static NestedNameSpecifier * Create(const ASTContext &Context, NestedNameSpecifier *Prefix, const IdentifierInfo *II)
Builds a specifier combining a prefix and an identifier.
NamespaceAliasDecl * getAsNamespaceAlias() const
Retrieve the namespace alias stored in this nested name specifier.
IdentifierInfo * getAsIdentifier() const
Retrieve the identifier stored in this nested name specifier.
NestedNameSpecifier * getPrefix() const
Return the prefix of this nested name specifier.
@ NamespaceAlias
A namespace alias, stored as a NamespaceAliasDecl*.
@ TypeSpec
A type, stored as a Type*.
@ TypeSpecWithTemplate
A type that was preceded by the 'template' keyword, stored as a Type*.
@ Super
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
@ Identifier
An identifier, stored as an IdentifierInfo*.
@ Global
The global specifier '::'. There is no stored value.
@ Namespace
A namespace, stored as a NamespaceDecl*.
NamespaceDecl * getAsNamespace() const
Retrieve the namespace stored in this nested name specifier.
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
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:2328
ObjCCategoryImplDecl - An object of this class encapsulates a category @implementation declaration.
Definition: DeclObjC.h:2544
ObjCContainerDecl - Represents a container for method declarations.
Definition: DeclObjC.h:947
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition: DeclObjC.h:2596
Represents an ObjC class declaration.
Definition: DeclObjC.h:1153
ObjCTypeParamList * getTypeParamList() const
Retrieve the type parameters of this class.
Definition: DeclObjC.cpp:322
static ObjCInterfaceDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation atLoc, const IdentifierInfo *Id, ObjCTypeParamList *typeParamList, ObjCInterfaceDecl *PrevDecl, SourceLocation ClassLoc=SourceLocation(), bool isInternal=false)
Definition: DeclObjC.cpp:1542
bool hasDefinition() const
Determine whether this class has been defined.
Definition: DeclObjC.h:1527
ivar_range ivars() const
Definition: DeclObjC.h:1450
bool ClassImplementsProtocol(ObjCProtocolDecl *lProto, bool lookupCategory, bool RHSIsQualifiedID=false)
ClassImplementsProtocol - Checks that 'lProto' protocol has been implemented in IDecl class,...
Definition: DeclObjC.cpp:1788
StringRef getObjCRuntimeNameAsString() const
Produce a name to be used for class's metadata.
Definition: DeclObjC.cpp:1613
ObjCImplementationDecl * getImplementation() const
Definition: DeclObjC.cpp:1629
ObjCInterfaceDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this Objective-C class.
Definition: DeclObjC.h:1914
ObjCInterfaceDecl * getSuperClass() const
Definition: DeclObjC.cpp:352
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:1809
known_extensions_range known_extensions() const
Definition: DeclObjC.h:1761
Interfaces are the core concept in Objective-C for object oriented design.
Definition: Type.h:7348
ObjCInterfaceDecl * getDecl() const
Get the declaration of this interface.
Definition: Type.cpp:903
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1951
ObjCIvarDecl * getNextIvar()
Definition: DeclObjC.h:1986
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: Type.h:7404
bool isObjCQualifiedClassType() const
True if this is equivalent to 'Class.
Definition: Type.h:7485
const ObjCObjectPointerType * stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const
Strip off the Objective-C "kindof" type and (with it) any protocol qualifiers.
Definition: Type.cpp:910
bool isObjCQualifiedIdType() const
True if this is equivalent to 'id.
Definition: Type.h:7479
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:7561
const ObjCObjectType * getObjectType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:7441
bool qual_empty() const
Definition: Type.h:7533
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition: Type.h:7462
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:7416
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition: Type.h:7456
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition: Type.cpp:1799
qual_range quals() const
Definition: Type.h:7523
bool isObjCClassType() const
True if this is equivalent to the 'Class' type, i.e.
Definition: Type.h:7468
A class providing a concrete implementation of ObjCObjectType, so as to not increase the footprint of...
Definition: Type.h:7301
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.cpp:4386
Represents a class type in Objective C.
Definition: Type.h:7150
bool isKindOfTypeAsWritten() const
Whether this is a "__kindof" type as written.
Definition: Type.h:7265
bool isSpecialized() const
Determine whether this object type is "specialized", meaning that it has type arguments.
Definition: Type.cpp:832
ArrayRef< QualType > getTypeArgsAsWritten() const
Retrieve the type arguments of this object type as they were written.
Definition: Type.h:7260
bool isObjCQualifiedClass() const
Definition: Type.h:7232
QualType getBaseType() const
Gets the base type of this object type.
Definition: Type.h:7212
bool isObjCClass() const
Definition: Type.h:7218
bool isKindOfType() const
Whether this ia a "__kindof" type (semantically).
Definition: Type.cpp:868
bool isObjCQualifiedId() const
Definition: Type.h:7231
ArrayRef< QualType > getTypeArgs() const
Retrieve the type arguments of this object type (semantically).
Definition: Type.cpp:850
bool isObjCUnqualifiedId() const
Definition: Type.h:7222
ObjCInterfaceDecl * getInterface() const
Gets the interface declaration for this object type, if the base type really is an interface.
Definition: Type.h:7383
QualType getSuperClassType() const
Retrieve the type of the superclass of this object type.
Definition: Type.h:7276
Represents one property declaration in an Objective-C interface.
Definition: DeclObjC.h:730
bool isReadOnly() const
isReadOnly - Return true iff the property has a setter.
Definition: DeclObjC.h:837
static ObjCPropertyDecl * findPropertyDecl(const DeclContext *DC, const IdentifierInfo *propertyID, ObjCPropertyQueryKind queryKind)
Lookup a property by name in the specified DeclContext.
Definition: DeclObjC.cpp:179
bool isOptional() const
Definition: DeclObjC.h:915
SetterKind getSetterKind() const
getSetterKind - Return the method used for doing assignment in the property setter.
Definition: DeclObjC.h:872
Selector getSetterName() const
Definition: DeclObjC.h:892
QualType getType() const
Definition: DeclObjC.h:803
Selector getGetterName() const
Definition: DeclObjC.h:884
ObjCPropertyAttribute::Kind getPropertyAttributes() const
Definition: DeclObjC.h:814
ObjCPropertyImplDecl - Represents implementation declaration of a property in a class or category imp...
Definition: DeclObjC.h:2804
ObjCIvarDecl * getPropertyIvarDecl() const
Definition: DeclObjC.h:2878
Represents an Objective-C protocol declaration.
Definition: DeclObjC.h:2083
protocol_range protocols() const
Definition: DeclObjC.h:2160
unsigned getNumProtocols() const
Return the number of qualifying protocols in this type, or 0 if there are none.
Definition: Type.h:7056
qual_iterator qual_end() const
Definition: Type.h:7050
qual_iterator qual_begin() const
Definition: Type.h:7049
qual_range quals() const
Definition: Type.h:7048
bool isGNUFamily() const
Is this runtime basically of the GNU family of runtimes?
Definition: ObjCRuntime.h:127
Represents the declaration of an Objective-C type parameter.
Definition: DeclObjC.h:578
ObjCTypeParamVariance getVariance() const
Determine the variance of this type parameter.
Definition: DeclObjC.h:623
Stores a list of Objective-C type parameters for a parameterized class or a category/extension thereo...
Definition: DeclObjC.h:659
Represents a type parameter type in Objective C.
Definition: Type.h:7076
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.cpp:4403
A structure for storing the information associated with an overloaded template name.
Definition: TemplateName.h:108
Represents a C++11 pack expansion that produces a sequence of expressions.
Definition: ExprCXX.h:4180
Represents a pack expansion of types.
Definition: Type.h:6965
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:6999
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:5866
Sugar for parentheses used when specifying types.
Definition: Type.h:3166
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3180
void clear()
Clear parent maps.
Represents a parameter to a function.
Definition: Decl.h:1722
ObjCDeclQualifier getObjCDeclQualifier() const
Definition: Decl.h:1786
QualType getOriginalType() const
Definition: Decl.cpp:2912
ParsedAttr - Represents a syntactic attribute.
Definition: ParsedAttr.h:129
PipeType - OpenCL20.
Definition: Type.h:7604
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:7621
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3192
QualType getPointeeType() const
Definition: Type.h:3202
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3207
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:137
A (possibly-)qualified type.
Definition: Type.h:941
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:7839
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition: Type.cpp:2751
Qualifiers::GC getObjCGCAttr() const
Returns gc attribute of this type.
Definition: Type.h:7886
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:7844
QualType withConst() const
Definition: Type.h:1166
bool hasLocalQualifiers() const
Determine whether this particular QualType instance has any qualifiers, without looking through any t...
Definition: Type.h:1068
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:1008
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7755
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:7881
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7795
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1444
QualType getCanonicalType() const
Definition: Type.h:7807
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:7849
SplitQualType split() const
Divides a QualType into its unqualified type and a set of local qualifiers.
Definition: Type.h:7776
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:7828
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition: Type.h:1542
bool isCanonical() const
Definition: Type.h:7812
const Type * getTypePtrOrNull() const
Definition: Type.h:7759
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:2888
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition: Type.h:7787
Represents a template name as written in source code.
Definition: TemplateName.h:434
void Profile(llvm::FoldingSetNodeID &ID)
Definition: TemplateName.h:471
A qualifier set is used to build a set of qualifiers.
Definition: Type.h:7695
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition: Type.h:7702
The collection of all-type qualifiers we support.
Definition: Type.h:319
unsigned getCVRQualifiers() const
Definition: Type.h:475
void removeCVRQualifiers(unsigned mask)
Definition: Type.h:482
GC getObjCGCAttr() const
Definition: Type.h:506
void addAddressSpace(LangAS space)
Definition: Type.h:584
static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R)
Returns the common set of qualifiers while removing them from the given sets.
Definition: Type.h:371
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:348
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition: Type.h:341
@ OCL_None
There is no lifetime qualification on this type.
Definition: Type.h:337
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:351
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition: Type.h:354
void removeObjCLifetime()
Definition: Type.h:538
bool hasNonFastQualifiers() const
Return true if the set contains any qualifiers which require an ExtQuals node to be allocated.
Definition: Type.h:625
void addConsistentQualifiers(Qualifiers qs)
Add the qualifiers from the given set to this set, given that they don't conflict.
Definition: Type.h:676
void removeFastQualifiers(unsigned mask)
Definition: Type.h:611
bool hasUnaligned() const
Definition: Type.h:498
bool hasAddressSpace() const
Definition: Type.h:557
unsigned getFastQualifiers() const
Definition: Type.h:606
void removeAddressSpace()
Definition: Type.h:583
void setAddressSpace(LangAS space)
Definition: Type.h:578
static bool isAddressSpaceSupersetOf(LangAS A, LangAS B)
Returns true if address space A is equal to or a superset of B.
Definition: Type.h:695
bool hasObjCGCAttr() const
Definition: Type.h:505
uint64_t getAsOpaqueValue() const
Definition: Type.h:442
bool hasObjCLifetime() const
Definition: Type.h:531
ObjCLifetime getObjCLifetime() const
Definition: Type.h:532
bool empty() const
Definition: Type.h:634
void addObjCGCAttr(GC type)
Definition: Type.h:511
LangAS getAddressSpace() const
Definition: Type.h:558
An rvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3495
unsigned getCommentBeginLine(RawComment *C, FileID File, unsigned Offset) const
const std::map< unsigned, RawComment * > * getCommentsInFile(FileID File) const
unsigned getCommentEndOffset(RawComment *C) const
void addComment(const RawComment &RC, const CommentOptions &CommentOpts, llvm::BumpPtrAllocator &Allocator)
bool isTrailingComment() const LLVM_READONLY
Returns true if it is a comment that should be put after a member:
SourceRange getSourceRange() const LLVM_READONLY
bool isDocumentation() const LLVM_READONLY
Returns true if this comment any kind of a documentation comment.
comments::FullComment * parse(const ASTContext &Context, const Preprocessor *PP, const Decl *D) const
Parse the comment, assuming it is attached to decl D.
Represents a struct/union/class.
Definition: Decl.h:4145
bool hasFlexibleArrayMember() const
Definition: Decl.h:4178
field_range fields() const
Definition: Decl.h:4351
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition: Decl.cpp:5014
virtual void completeDefinition()
Note that the definition of this type is now complete.
Definition: Decl.cpp:5080
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:4336
bool field_empty() const
Definition: Decl.h:4359
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5970
RecordDecl * getDecl() const
Definition: Type.h:5980
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Definition: Redeclarable.h:217
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
Definition: Redeclarable.h:205
decl_type * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
Definition: Redeclarable.h:227
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: Redeclarable.h:297
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3433
QualType getPointeeType() const
Definition: Type.h:3451
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3459
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.
DiagnosticsEngine & getDiagnostics() const
StringRef getBufferData(FileID FID, bool *Invalid=nullptr) const
Return a StringRef to the source buffer data for the specified FileID.
SourceLocation getSpellingLoc(SourceLocation Loc) const
Given a SourceLocation object, return the spelling location referenced by the ID.
unsigned getLineNumber(FileID FID, unsigned FilePos, bool *Invalid=nullptr) const
Given a SourceLocation, return the spelling line number for the position indicated.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
std::pair< FileID, unsigned > getDecomposedLoc(SourceLocation Loc) const
Decompose the specified location into a raw FileID + Offset pair.
SourceLocation getExpansionLoc(SourceLocation Loc) const
Given a SourceLocation object Loc, return the expansion location referenced by the ID.
A trivial tuple used to represent a source range.
SourceLocation getBegin() const
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, bool Canonical, bool ProfileLambdaExpr=false) const
Produce a unique representation of the given statement.
The streaming interface shared between DiagnosticBuilder and PartialDiagnostic.
Definition: Diagnostic.h:1115
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1778
static StringLiteral * Create(const ASTContext &Ctx, StringRef Str, StringLiteralKind Kind, bool Pascal, QualType Ty, const SourceLocation *Loc, unsigned NumConcatenated)
This is the "fully general" constructor that allows representation of strings formed from multiple co...
Definition: Expr.cpp:1191
A structure for storing an already-substituted template template parameter pack.
Definition: TemplateName.h:141
Decl * getAssociatedDecl() const
A template-like entity which owns the whole pattern being substituted.
void Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context)
TemplateTemplateParmDecl * getParameterPack() const
Retrieve the template template parameter pack being substituted.
TemplateArgument getArgumentPack() const
Retrieve the template template argument pack with which this parameter was substituted.
unsigned getIndex() const
Returns the index of the replaced parameter in the associated declaration.
Definition: TemplateName.h:156
A structure for storing the information associated with a substituted template template parameter.
Definition: TemplateName.h:375
void Profile(llvm::FoldingSetNodeID &ID)
TemplateTemplateParmDecl * getParameter() const
Represents the result of substituting a set of types for a template type parameter pack.
Definition: Type.h:6288
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.cpp:4248
Represents the result of substituting a type for a template type parameter.
Definition: Type.h:6218
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:6257
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3561
TypedefNameDecl * getTypedefNameForAnonDecl() const
Definition: Decl.h:3789
void startDefinition()
Starts the definition of this tag declaration.
Definition: Decl.cpp:4736
bool isUnion() const
Definition: Decl.h:3767
TagDecl * getDecl() const
Definition: Type.cpp:4076
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:136
Kind
The basic C++ ABI kind.
Definition: TargetCXXABI.h:31
static Kind getKind(StringRef Name)
Definition: TargetCXXABI.h:59
Exposes information about the current target.
Definition: TargetInfo.h:218
TargetOptions & getTargetOpts() const
Retrieve the target options.
Definition: TargetInfo.h:312
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1256
IntType getInt64Type() const
Definition: TargetInfo.h:405
unsigned getMaxAtomicInlineWidth() const
Return the maximum width lock-free atomic operation which can be inlined given the supported features...
Definition: TargetInfo.h:834
virtual LangAS getCUDABuiltinAddressSpace(unsigned AS) const
Map from the address space field in builtin description strings to the language address space.
Definition: TargetInfo.h:1639
virtual LangAS getOpenCLBuiltinAddressSpace(unsigned AS) const
Map from the address space field in builtin description strings to the language address space.
Definition: TargetInfo.h:1633
unsigned getDefaultAlignForAttributeAligned() const
Return the default alignment for attribute((aligned)) on this target, to be used if no alignment valu...
Definition: TargetInfo.h:727
unsigned getBFloat16Width() const
getBFloat16Width/Align/Format - Return the size/align/format of '__bf16'.
Definition: TargetInfo.h:772
BuiltinVaListKind
The different kinds of __builtin_va_list types defined by the target implementation.
Definition: TargetInfo.h:319
@ AArch64ABIBuiltinVaList
__builtin_va_list as defined by the AArch64 ABI http://infocenter.arm.com/help/topic/com....
Definition: TargetInfo.h:328
@ PNaClABIBuiltinVaList
__builtin_va_list as defined by the PNaCl ABI: http://www.chromium.org/nativeclient/pnacl/bitcode-abi...
Definition: TargetInfo.h:332
@ PowerABIBuiltinVaList
__builtin_va_list as defined by the Power ABI: https://www.power.org /resources/downloads/Power-Arch-...
Definition: TargetInfo.h:337
@ AAPCSABIBuiltinVaList
__builtin_va_list as defined by ARM AAPCS ABI http://infocenter.arm.com
Definition: TargetInfo.h:346
@ CharPtrBuiltinVaList
typedef char* __builtin_va_list;
Definition: TargetInfo.h:321
@ VoidPtrBuiltinVaList
typedef void* __builtin_va_list;
Definition: TargetInfo.h:324
@ X86_64ABIBuiltinVaList
__builtin_va_list as defined by the x86-64 ABI: http://refspecs.linuxbase.org/elf/x86_64-abi-0....
Definition: TargetInfo.h:341
virtual uint64_t getNullPointerValue(LangAS AddrSpace) const
Get integer value for null pointer.
Definition: TargetInfo.h:488
uint64_t getPointerWidth(LangAS AddrSpace) const
Return the width of pointers on this target, for the specified address space.
Definition: TargetInfo.h:472
static bool isTypeSigned(IntType T)
Returns true if the type is signed; false otherwise.
Definition: TargetInfo.cpp:370
unsigned getHalfAlign() const
Definition: TargetInfo.h:763
unsigned getBFloat16Align() const
Definition: TargetInfo.h:773
FloatModeKind getRealTypeByWidth(unsigned BitWidth, FloatModeKind ExplicitType) const
Return floating point type with specified width.
Definition: TargetInfo.cpp:316
virtual IntType getIntTypeByWidth(unsigned BitWidth, bool IsSigned) const
Return integer type with specified width.
Definition: TargetInfo.cpp:286
unsigned getHalfWidth() const
getHalfWidth/Align/Format - Return the size/align/format of 'half'.
Definition: TargetInfo.h:762
unsigned getMaxAlignedAttribute() const
Get the maximum alignment in bits for a static variable with aligned attribute.
Definition: TargetInfo.h:947
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:735
unsigned getTargetAddressSpace(LangAS AS) const
Definition: TargetInfo.h:1620
unsigned getFloat128Width() const
getFloat128Width/Align/Format - Return the size/align/format of '__float128'.
Definition: TargetInfo.h:791
const llvm::fltSemantics & getLongDoubleFormat() const
Definition: TargetInfo.h:785
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1327
bool hasAArch64SVETypes() const
Returns whether or not the AArch64 SVE built-in types are available on this target.
Definition: TargetInfo.h:1040
bool useAddressSpaceMapMangling() const
Specify if mangling based on address space map should be used or not for language specific address sp...
Definition: TargetInfo.h:998
unsigned getLongWidth() const
getLongWidth/Align - Return the size of 'signed long' and 'unsigned long' for this target,...
Definition: TargetInfo.h:514
unsigned getFloat128Align() const
Definition: TargetInfo.h:792
virtual bool hasBFloat16Type() const
Determine whether the _BFloat16 type is supported on this target.
Definition: TargetInfo.h:699
const llvm::fltSemantics & getFloat128Format() const
Definition: TargetInfo.h:793
unsigned getLongDoubleWidth() const
getLongDoubleWidth/Align/Format - Return the size/align/format of 'long double'.
Definition: TargetInfo.h:783
unsigned getLongDoubleAlign() const
Definition: TargetInfo.h:784
virtual std::optional< std::pair< unsigned, unsigned > > getVScaleRange(const LangOptions &LangOpts) const
Returns target-specific min and max values VScale_Range.
Definition: TargetInfo.h:1017
llvm::StringMap< bool > FeatureMap
The map of which features have been enabled disabled based on the command line.
Definition: TargetOptions.h:62
A convenient class for passing around template argument information.
Definition: TemplateBase.h:632
SourceLocation getRAngleLoc() const
Definition: TemplateBase.h:648
llvm::ArrayRef< TemplateArgumentLoc > arguments() const
Definition: TemplateBase.h:659
SourceLocation getLAngleLoc() const
Definition: TemplateBase.h:647
A template argument list.
Definition: DeclTemplate.h:244
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
Definition: DeclTemplate.h:274
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:524
Represents a template argument.
Definition: TemplateBase.h:61
QualType getStructuralValueType() const
Get the type of a StructuralValue.
Definition: TemplateBase.h:399
QualType getParamTypeForDecl() const
Definition: TemplateBase.h:331
Expr * getAsExpr() const
Retrieve the template argument as an expression.
Definition: TemplateBase.h:408
std::optional< unsigned > getNumTemplateExpansions() const
Retrieve the number of expansions that a template template argument expansion will produce,...
QualType getAsType() const
Retrieve the type for a type template argument.
Definition: TemplateBase.h:319
QualType getNullPtrType() const
Retrieve the type for null non-type template argument.
Definition: TemplateBase.h:337
static TemplateArgument CreatePackCopy(ASTContext &Context, ArrayRef< TemplateArgument > Args)
Create a new template argument pack by copying the given set of template arguments.
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
Definition: TemplateBase.h:343
bool structurallyEquals(const TemplateArgument &Other) const
Determines whether two template arguments are superficially the same.
QualType getIntegralType() const
Retrieve the type of the integral value.
Definition: TemplateBase.h:377
bool getIsDefaulted() const
If returns 'true', this TemplateArgument corresponds to a default template parameter.
Definition: TemplateBase.h:393
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
Definition: TemplateBase.h:326
ArrayRef< TemplateArgument > pack_elements() const
Iterator range referencing all of the elements of a template argument pack.
Definition: TemplateBase.h:432
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
Definition: TemplateBase.h:74
@ Template
The template argument is a template name that was provided for a template template parameter.
Definition: TemplateBase.h:93
@ StructuralValue
The template argument is a non-type template argument that can't be represented by the special-case D...
Definition: TemplateBase.h:89
@ Pack
The template argument is actually a parameter pack.
Definition: TemplateBase.h:107
@ TemplateExpansion
The template argument is a pack expansion of a template name that was provided for a template templat...
Definition: TemplateBase.h:97
@ NullPtr
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
Definition: TemplateBase.h:78
@ Type
The template argument is a type.
Definition: TemplateBase.h:70
@ Null
Represents an empty template argument, e.g., one that has not been deduced.
Definition: TemplateBase.h:67
@ Integral
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
Definition: TemplateBase.h:82
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
Definition: TemplateBase.h:103
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:295
TemplateName getAsTemplateOrTemplatePattern() const
Retrieve the template argument as a template name; if the argument is a pack expansion,...
Definition: TemplateBase.h:350
const APValue & getAsStructuralValue() const
Get the value of a StructuralValue.
Definition: TemplateBase.h:396
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:394
bool isTypeAlias() const
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:413
Represents a C++ template name within the type system.
Definition: TemplateName.h:203
TemplateDecl * getAsTemplateDecl() const
Retrieve the underlying template declaration that this template name refers to, if known.
DependentTemplateName * getAsDependentTemplateName() const
Retrieve the underlying dependent template name structure, if any.
NameKind getKind() const
void * getAsVoidPointer() const
Retrieve the template name as a void pointer.
Definition: TemplateName.h:355
@ UsingTemplate
A template name that refers to a template declaration found through a specific using shadow declarati...
Definition: TemplateName.h:248
@ OverloadedTemplate
A set of overloaded template declarations.
Definition: TemplateName.h:223
@ Template
A single template declaration.
Definition: TemplateName.h:220
@ DependentTemplate
A dependent template name that has not been resolved to a template (or set of templates).
Definition: TemplateName.h:235
@ SubstTemplateTemplateParm
A template template parameter that has been substituted for some other template name.
Definition: TemplateName.h:239
@ SubstTemplateTemplateParmPack
A template template parameter pack that has been substituted for a template template argument pack,...
Definition: TemplateName.h:244
@ QualifiedTemplate
A qualified template name, where the qualification is kept to describe the source code as written.
Definition: TemplateName.h:231
@ AssumedTemplate
An unqualified-id that has been assumed to name a function template that will be found by ADL.
Definition: TemplateName.h:227
A template parameter object.
static void Profile(llvm::FoldingSetNodeID &ID, QualType T, const APValue &V)
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:73
NamedDecl * getParam(unsigned Idx)
Definition: DeclTemplate.h:144
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
NamedDecl *const * const_iterator
Iterates through the template parameters in this list.
Definition: DeclTemplate.h:129
Expr * getRequiresClause()
The constraint-expression of the associated requires-clause.
Definition: DeclTemplate.h:180
void setArgLocInfo(unsigned i, TemplateArgumentLocInfo AI)
Definition: TypeLoc.h:1687
void setTemplateKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:1663
void setTemplateNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:1704
void setLAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1671
void setRAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1679
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:6485
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition: Type.cpp:4338
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
unsigned getPosition() const
Get the position of the template parameter within its parameter list.
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.
bool isExpandedParameterPack() const
Whether this parameter is a template template parameter pack that has a known list of different templ...
static TemplateTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation L, unsigned D, unsigned P, bool ParameterPack, IdentifierInfo *Id, bool Typename, TemplateParameterList *Params)
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, std::optional< unsigned > NumExpanded=std::nullopt)
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:6190
Models the abbreviated syntax to constrain a template type parameter: template <convertible_to<string...
Definition: ASTConcept.h:227
ConceptDecl * getNamedConcept() const
Definition: ASTConcept.h:250
Expr * getImmediatelyDeclaredConstraint() const
Get the immediately-declared constraint expression introduced by this type-constraint,...
Definition: ASTConcept.h:242
ConceptReference * getConceptReference() const
Definition: ASTConcept.h:246
Represents a declaration of a type.
Definition: Decl.h:3367
void setTypeForDecl(const Type *TD)
Definition: Decl.h:3392
const Type * getTypeForDecl() const
Definition: Decl.h:3391
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:94
void initialize(ASTContext &Context, SourceLocation Loc) const
Initializes this to state that every location in this type is the given location.
Definition: TypeLoc.h:200
Represents a typeof (or typeof) expression (a C23 feature and GCC extension) or a typeof_unqual expre...
Definition: Type.h:5702
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition: Type.h:5752
A container of type source information.
Definition: Type.h:7726
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:256
The base class of the type hierarchy.
Definition: Type.h:1829
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1882
bool isBlockPointerType() const
Definition: Type.h:8022
bool isVoidType() const
Definition: Type.h:8324
bool isBooleanType() const
Definition: Type.h:8452
bool isFunctionReferenceType() const
Definition: Type.h:8055
bool isObjCBuiltinType() const
Definition: Type.h:8201
QualType getRVVEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an RVV builtin type.
Definition: Type.cpp:2579
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:740
bool isIncompleteArrayType() const
Definition: Type.h:8088
bool isPlaceholderType() const
Test for a type which does not represent an actual type-system type but is instead used as a placehol...
Definition: Type.h:8300
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition: Type.cpp:2146
bool isConstantArrayType() const
Definition: Type.h:8084
bool hasIntegerRepresentation() const
Determine whether this type has an integer representation of some sort, e.g., it is an integer type o...
Definition: Type.cpp:2021
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition: Type.cpp:2352
bool isArrayType() const
Definition: Type.h:8080
bool isCharType() const
Definition: Type.cpp:2089
QualType getLocallyUnqualifiedSingleStepDesugaredType() const
Pull a single level of sugar off of this locally-unqualified type.
Definition: Type.cpp:476
bool isFunctionPointerType() const
Definition: Type.h:8048
bool isPointerType() const
Definition: Type.h:8008
bool isArrayParameterType() const
Definition: Type.h:8096
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:8364
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8612
bool isSpecificPlaceholderType(unsigned K) const
Test for a specific placeholder type.
Definition: Type.h:8313
bool isSignedFixedPointType() const
Return true if this is a fixed point type that is signed according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8405
bool isEnumeralType() const
Definition: Type.h:8112
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition: Type.cpp:2510
bool isObjCQualifiedIdType() const
Definition: Type.h:8171
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:705
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:8439
bool hasUnsignedIntegerRepresentation() const
Determine whether this type has an unsigned integer representation of some sort, e....
Definition: Type.cpp:2236
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition: Type.cpp:2548
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.h:2805
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2708
bool isBitIntType() const
Definition: Type.h:8246
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:8293
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition: Type.h:8104
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2700
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8377
bool isSaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8393
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition: Type.h:2359
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
Definition: Type.cpp:2186
QualType getCanonicalTypeInternal() const
Definition: Type.h:2983
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:8495
bool isMemberPointerType() const
Definition: Type.h:8062
bool isObjCIdType() const
Definition: Type.h:8183
bool isUnsaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8401
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition: Type.h:8598
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2362
bool isFunctionType() const
Definition: Type.h:8004
bool isObjCObjectPointerType() const
Definition: Type.h:8150
bool isUnsignedFixedPointType() const
Return true if this is a fixed point type that is unsigned according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8419
bool isVectorType() const
Definition: Type.h:8120
bool isObjCClassType() const
Definition: Type.h:8189
bool isRVVVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'riscv_rvv_vector_bits' type attribute,...
Definition: Type.cpp:2561
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition: Type.cpp:2497
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:2196
bool isAnyPointerType() const
Definition: Type.h:8016
TypeClass getTypeClass() const
Definition: Type.h:2339
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition: Type.h:2365
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8545
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition: Type.cpp:605
bool isNullPtrType() const
Definition: Type.h:8357
bool isRecordType() const
Definition: Type.h:8108
bool isObjCRetainableType() const
Definition: Type.cpp:4950
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition: Type.cpp:4693
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition: Decl.h:3511
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition: Decl.cpp:5502
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3409
QualType getUnderlyingType() const
Definition: Decl.h:3464
void setTypeSourceInfo(TypeSourceInfo *newType)
Definition: Decl.h:3471
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:5655
A unary type transform, which is a type constructed from another.
Definition: Type.h:5887
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
Definition: DeclCXX.h:4350
static void Profile(llvm::FoldingSetNodeID &ID, QualType Ty, const APValue &APVal)
Definition: DeclCXX.h:4378
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:35
Represents the dependent type named by a dependently-scoped typename using declaration,...
Definition: Type.h:5572
Represents a dependent using declaration which was marked with typename.
Definition: DeclCXX.h:3963
Represents a C++ using-enum-declaration.
Definition: DeclCXX.h:3717
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition: DeclCXX.h:3324
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:5623
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:667
void setType(QualType newType)
Definition: Decl.h:679
QualType getType() const
Definition: Decl.h:678
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition: Decl.cpp:5364
void clear()
Definition: Value.cpp:218
Represents a variable declaration or definition.
Definition: Decl.h:879
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition: Decl.cpp:2775
bool hasInit() const
Definition: Decl.cpp:2380
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:2426
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1231
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition: Decl.h:1156
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition: Decl.cpp:2737
bool isInline() const
Whether this variable is (C++1z) inline.
Definition: Decl.h:1492
@ DeclarationOnly
This declaration is only a declaration.
Definition: Decl.h:1243
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition: Decl.cpp:2357
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:2744
Represents a C array with a specified size that is not an integer-constant-expression.
Definition: Type.h:3800
Expr * getSizeExpr() const
Definition: Type.h:3819
Represents a GCC generic vector type.
Definition: Type.h:4026
unsigned getNumElements() const
Definition: Type.h:4041
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:4050
VectorKind getVectorKind() const
Definition: Type.h:4046
QualType getElementType() const
Definition: Type.h:4040
A full comment attached to a declaration, contains block content.
Definition: Comment.h:1083
ArrayRef< BlockContentComment * > getBlocks() const
Definition: Comment.h:1121
const DeclInfo * getDeclInfo() const LLVM_READONLY
Definition: Comment.h:1115
const Decl * getDecl() const LLVM_READONLY
Definition: Comment.h:1111
Holds all information required to evaluate constexpr code in a module.
Definition: Context.h:40
Defines the Linkage enumeration and various utility functions.
Defines the clang::TargetInfo interface.
SmallVector< BoundNodes, 1 > match(MatcherT Matcher, const NodeT &Node, ASTContext &Context)
Returns the results of matching Matcher on Node.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const AstTypeMatcher< ArrayType > arrayType
Matches all kinds of arrays.
const AstTypeMatcher< TagType > tagType
Matches tag types (record and enum types).
The JSON file list parser is used to communicate input to InstallAPI.
@ Vector
'vector' clause, allowed on 'loop', Combined, and 'routine' directives.
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:21
@ OpenCL
Definition: LangStandard.h:66
@ CPlusPlus20
Definition: LangStandard.h:60
@ CPlusPlus
Definition: LangStandard.h:56
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: Type.h:1788
OpenCLTypeKind
OpenCL type kinds.
Definition: TargetInfo.h:204
@ OCLTK_ReserveID
Definition: TargetInfo.h:211
@ OCLTK_Sampler
Definition: TargetInfo.h:212
@ OCLTK_Pipe
Definition: TargetInfo.h:209
@ OCLTK_ClkEvent
Definition: TargetInfo.h:206
@ OCLTK_Event
Definition: TargetInfo.h:207
@ OCLTK_Default
Definition: TargetInfo.h:205
@ OCLTK_Queue
Definition: TargetInfo.h:210
FunctionType::ExtInfo getFunctionExtInfo(const Type &t)
Definition: Type.h:7908
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
@ ICIS_NoInit
No in-class initializer.
Definition: Specifiers.h:272
CXXABI * CreateMicrosoftCXXABI(ASTContext &Ctx)
TypeOfKind
The kind of 'typeof' expression we're after.
Definition: Type.h:922
@ SC_Register
Definition: Specifiers.h:257
@ SC_Static
Definition: Specifiers.h:252
CXXABI * CreateItaniumCXXABI(ASTContext &Ctx)
Creates an instance of a C++ ABI class.
const StreamingDiagnostic & operator<<(const StreamingDiagnostic &DB, const ASTContext::SectionInfo &Section)
Insertion operator for diagnostics.
@ TypeAlignment
Definition: Type.h:73
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have.
Definition: Linkage.h:24
@ External
External linkage, which indicates that the entity can be referred to from other translation units.
@ Result
The result type of a method or function.
ArraySizeModifier
Capture whether this is a normal array (e.g.
Definition: Type.h:3568
bool isComputedNoexcept(ExceptionSpecificationType ESpecType)
TagTypeKind
The kind of a tag type.
Definition: Type.h:6695
@ Interface
The "__interface" keyword.
@ Struct
The "struct" keyword.
@ Class
The "class" keyword.
bool isDiscardableGVALinkage(GVALinkage L)
Definition: Linkage.h:80
BuiltinTemplateKind
Kinds of BuiltinTemplateDecl.
Definition: Builtins.h:307
@ BTK__type_pack_element
This names the __type_pack_element BuiltinTemplateDecl.
Definition: Builtins.h:312
@ BTK__make_integer_seq
This names the __make_integer_seq BuiltinTemplateDecl.
Definition: Builtins.h:309
LangAS
Defines the address space values used by the address space qualifier of QualType.
Definition: AddressSpaces.h:25
TranslationUnitKind
Describes the kind of translation unit being processed.
Definition: LangOptions.h:1065
FloatModeKind
Definition: TargetInfo.h:72
bool isPtrSizeAddressSpace(LangAS AS)
Definition: AddressSpaces.h:91
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:132
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:135
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition: Specifiers.h:144
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:139
const FunctionProtoType * T
void printTemplateArgumentList(raw_ostream &OS, ArrayRef< TemplateArgument > Args, const PrintingPolicy &Policy, const TemplateParameterList *TPL=nullptr)
Print a template argument list, including the '<' and '>' enclosing the template arguments.
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1275
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:188
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition: Specifiers.h:206
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:202
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition: Specifiers.h:198
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:194
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition: Specifiers.h:191
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:278
@ CC_C
Definition: Specifiers.h:279
@ CC_M68kRTD
Definition: Specifiers.h:300
@ CC_X86RegCall
Definition: Specifiers.h:287
@ CC_X86VectorCall
Definition: Specifiers.h:283
@ CC_X86StdCall
Definition: Specifiers.h:280
@ CC_X86FastCall
Definition: Specifiers.h:281
@ Invariant
The parameter is invariant: must match exactly.
@ Contravariant
The parameter is contravariant, e.g., X<T> is a subtype of X when the type parameter is covariant and...
@ Covariant
The parameter is covariant, e.g., X<T> is a subtype of X when the type parameter is covariant and T i...
VectorKind
Definition: Type.h:3985
@ AltiVecBool
is AltiVec 'vector bool ...'
@ SveFixedLengthData
is AArch64 SVE fixed-length data vector
@ AltiVecPixel
is AltiVec 'vector Pixel'
@ Generic
not a target-specific vector type
@ RVVFixedLengthData
is RISC-V RVV fixed-length data vector
@ RVVFixedLengthMask
is RISC-V RVV fixed-length mask vector
@ SveFixedLengthPredicate
is AArch64 SVE fixed-length predicate vector
LangAS getLangASFromTargetAS(unsigned TargetAS)
Definition: AddressSpaces.h:86
AlignRequirementKind
Definition: ASTContext.h:143
@ None
The alignment was not explicit in code.
@ RequiredByEnum
The alignment comes from an alignment attribute on a enum type.
@ RequiredByTypedef
The alignment comes from an alignment attribute on a typedef.
@ RequiredByRecord
The alignment comes from an alignment attribute on a record type.
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition: Type.h:6670
@ None
No keyword precedes the qualified type name.
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
ExceptionSpecificationType
The various types of exception specifications that exist in C++11.
@ EST_DependentNoexcept
noexcept(expression), value-dependent
@ EST_DynamicNone
throw()
@ EST_Uninstantiated
not instantiated yet
@ EST_Unparsed
not parsed yet
@ EST_NoThrow
Microsoft __declspec(nothrow) extension.
@ EST_None
no exception specification
@ EST_MSAny
Microsoft throw(...) extension.
@ EST_BasicNoexcept
noexcept
@ EST_NoexceptFalse
noexcept(expression), evals to 'false'
@ EST_Unevaluated
not evaluated yet, for special member function
@ EST_NoexceptTrue
noexcept(expression), evals to 'true'
@ EST_Dynamic
throw(T1, T2)
@ AS_public
Definition: Specifiers.h:124
unsigned long uint64_t
unsigned NumTemplateArgs
The number of template arguments in TemplateArgs.
Definition: TemplateBase.h:694
Copy initialization expr of a __block variable and a boolean flag that indicates whether the expressi...
Definition: Expr.h:6411
Expr * getCopyExpr() const
Definition: Expr.h:6418
bool ParseAllComments
Treat ordinary comments as documentation comments.
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
Holds information about the various types of exception specification.
Definition: Type.h:5064
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: Type.h:5066
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition: Type.h:5069
Expr * NoexceptExpr
Noexcept expression, if this is a computed noexcept specification.
Definition: Type.h:5072
Extra information about a function prototype.
Definition: Type.h:5092
ExceptionSpecInfo ExceptionSpec
Definition: Type.h:5099
bool requiresFunctionProtoTypeArmAttributes() const
Definition: Type.h:5124
FunctionEffectsRef FunctionEffects
Definition: Type.h:5102
const ExtParameterInfo * ExtParameterInfos
Definition: Type.h:5100
bool requiresFunctionProtoTypeExtraBitfields() const
Definition: Type.h:5118
FunctionType::ExtInfo ExtInfo
Definition: Type.h:5093
A simple holder for a QualType representing a type in an exception specification.
Definition: Type.h:4551
A holder for Arm type attributes as described in the Arm C/C++ Language extensions which are not part...
Definition: Type.h:4612
A simple holder for various uncommon bits which do not fit in FunctionTypeBitfields.
Definition: Type.h:4556
A lazy value (of type T) that is within an AST node of type Owner, where the value might change in la...
Parts of a decomposed MSGuidDecl.
Definition: DeclCXX.h:4268
Contains information gathered from parsing the contents of TargetAttr.
Definition: TargetInfo.h:57
Describes how types, statements, expressions, and declarations should be printed.
Definition: PrettyPrinter.h:57
A std::pair-like structure for storing a qualified type split into its local qualifiers and its local...
Definition: Type.h:874
const Type * Ty
The locally-unqualified type.
Definition: Type.h:876
Qualifiers Quals
The local qualifiers.
Definition: Type.h:879
A this pointer adjustment.
Definition: Thunk.h:92
IntType
===-— Target Data Type Query Methods ----------------------------—===//
Definition: TargetInfo.h:142
AlignRequirementKind AlignRequirement
Definition: ASTContext.h:174
bool isAlignRequired()
Definition: ASTContext.h:166
AlignRequirementKind AlignRequirement
Definition: ASTContext.h:160
uint64_t Width
Definition: ASTContext.h:158
unsigned Align
Definition: ASTContext.h:159
Information about the declaration, useful to clients of FullComment.
Definition: Comment.h:962
const TemplateParameterList * TemplateParameters
Template parameters that can be referenced by \tparam if CommentDecl is a template (IsTemplateDecl or...
Definition: Comment.h:988
const Decl * CommentDecl
Declaration the comment is actually attached to (in the source).
Definition: Comment.h:965