clang 24.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"
18#include "clang/AST/ASTLambda.h"
22#include "clang/AST/Attr.h"
24#include "clang/AST/CharUnits.h"
25#include "clang/AST/Comment.h"
26#include "clang/AST/Decl.h"
27#include "clang/AST/DeclBase.h"
28#include "clang/AST/DeclCXX.h"
30#include "clang/AST/DeclObjC.h"
35#include "clang/AST/Expr.h"
36#include "clang/AST/ExprCXX.h"
38#include "clang/AST/Mangle.h"
44#include "clang/AST/Stmt.h"
47#include "clang/AST/Type.h"
48#include "clang/AST/TypeLoc.h"
57#include "clang/Basic/LLVM.h"
59#include "clang/Basic/Linkage.h"
60#include "clang/Basic/Module.h"
70#include "clang/Lex/MacroInfo.h"
71#include "llvm/ADT/APFixedPoint.h"
72#include "llvm/ADT/APInt.h"
73#include "llvm/ADT/APSInt.h"
74#include "llvm/ADT/ArrayRef.h"
75#include "llvm/ADT/DenseMap.h"
76#include "llvm/ADT/DenseSet.h"
77#include "llvm/ADT/FoldingSet.h"
78#include "llvm/ADT/PointerUnion.h"
79#include "llvm/ADT/STLExtras.h"
80#include "llvm/ADT/SmallPtrSet.h"
81#include "llvm/ADT/SmallVector.h"
82#include "llvm/ADT/StringExtras.h"
83#include "llvm/ADT/StringRef.h"
84#include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
85#include "llvm/Support/Capacity.h"
86#include "llvm/Support/Casting.h"
87#include "llvm/Support/Compiler.h"
88#include "llvm/Support/ErrorHandling.h"
89#include "llvm/Support/MD5.h"
90#include "llvm/Support/MathExtras.h"
91#include "llvm/Support/SipHash.h"
92#include "llvm/Support/raw_ostream.h"
93#include "llvm/TargetParser/AArch64TargetParser.h"
94#include "llvm/TargetParser/RISCVTargetParser.h"
95#include "llvm/TargetParser/Triple.h"
96#include <algorithm>
97#include <cassert>
98#include <cstddef>
99#include <cstdint>
100#include <cstdlib>
101#include <map>
102#include <memory>
103#include <optional>
104#include <string>
105#include <tuple>
106#include <utility>
107
108using namespace clang;
109
120
121/// \returns The locations that are relevant when searching for Doc comments
122/// related to \p Key.
125 SourceManager &SourceMgr) {
126 if (const auto *MI = dyn_cast<const MacroInfo *>(Key)) {
127 SourceLocation DefLoc = MI->getDefinitionLoc();
128 if (DefLoc.isInvalid() || !DefLoc.isFileID())
129 return {};
130
131 // The macro's definition location points at its name (e.g. FOO in
132 // `#define FOO 1`). The text between a preceding documentation comment
133 // and the name contains the `#define` directive itself, which would be
134 // rejected by the preprocessor-directive guard in
135 // getRawCommentNoCacheImpl. Walk back to the leading `#` so that
136 // the guard only fires when something *else* sits between the comment
137 // and our directive.
138 FileIDAndOffset Decomposed = SourceMgr.getDecomposedLoc(DefLoc);
139 bool Invalid = false;
140 StringRef Buffer = SourceMgr.getBufferData(Decomposed.first, &Invalid);
141 if (Invalid)
142 return {};
143 unsigned Offset = Decomposed.second;
144 if (size_t Found = Buffer.find_last_of("#\n", Offset);
145 Found != StringRef::npos)
146 Offset = Found;
147 return {SourceMgr.getLocForStartOfFile(Decomposed.first)
148 .getLocWithOffset(Offset)};
149 }
150
151 const auto *D = cast<const Decl *>(Key);
152 assert(D);
153
154 // User can not attach documentation to implicit declarations.
155 if (D->isImplicit())
156 return {};
157
158 // User can not attach documentation to implicit instantiations.
159 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
160 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
161 return {};
162 }
163
164 if (const auto *VD = dyn_cast<VarDecl>(D)) {
165 if (VD->isStaticDataMember() &&
166 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
167 return {};
168 }
169
170 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
171 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
172 return {};
173 }
174
175 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
176 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
177 if (TSK == TSK_ImplicitInstantiation ||
178 TSK == TSK_Undeclared)
179 return {};
180 }
181
182 if (const auto *ED = dyn_cast<EnumDecl>(D)) {
183 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
184 return {};
185 }
186 if (const auto *TD = dyn_cast<TagDecl>(D)) {
187 // When tag declaration (but not definition!) is part of the
188 // decl-specifier-seq of some other declaration, it doesn't get comment
189 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
190 return {};
191 }
192 // TODO: handle comments for function parameters properly.
193 if (isa<ParmVarDecl>(D))
194 return {};
195
196 // TODO: we could look up template parameter documentation in the template
197 // documentation.
201 return {};
202
204 // Find declaration location.
205 // For Objective-C declarations we generally don't expect to have multiple
206 // declarators, thus use declaration starting location as the "declaration
207 // location".
208 // For all other declarations multiple declarators are used quite frequently,
209 // so we use the location of the identifier as the "declaration location".
210 SourceLocation BaseLocation;
214 // Allow association with Y across {} in `typedef struct X {} Y`.
216 BaseLocation = D->getBeginLoc();
217 else
218 BaseLocation = D->getLocation();
219
220 if (!D->getLocation().isMacroID()) {
221 Locations.emplace_back(BaseLocation);
222 } else {
223 const auto *DeclCtx = D->getDeclContext();
224
225 // When encountering definitions generated from a macro (that are not
226 // contained by another declaration in the macro) we need to try and find
227 // the comment at the location of the expansion but if there is no comment
228 // there we should retry to see if there is a comment inside the macro as
229 // well. To this end we return first BaseLocation to first look at the
230 // expansion site, the second value is the spelling location of the
231 // beginning of the declaration defined inside the macro.
232 if (!(DeclCtx &&
233 Decl::castFromDeclContext(DeclCtx)->getLocation().isMacroID())) {
234 Locations.emplace_back(SourceMgr.getExpansionLoc(BaseLocation));
235 }
236
237 // We use Decl::getBeginLoc() and not just BaseLocation here to ensure that
238 // we don't refer to the macro argument location at the expansion site (this
239 // can happen if the name's spelling is provided via macro argument), and
240 // always to the declaration itself.
241 Locations.emplace_back(SourceMgr.getSpellingLoc(D->getBeginLoc()));
242 }
243
244 return Locations;
245}
246
248 RawCommentLookupKey Key, const SourceLocation RepresentativeLoc,
249 const std::map<unsigned, RawComment *> &CommentsInTheFile) const {
250 // If the declaration doesn't map directly to a location in a file, we
251 // can't find the comment.
252 if (RepresentativeLoc.isInvalid() || !RepresentativeLoc.isFileID())
253 return nullptr;
254
255 // If there are no comments anywhere, we won't find anything.
256 if (CommentsInTheFile.empty())
257 return nullptr;
258
259 const auto *D = dyn_cast<const Decl *>(Key);
260 const bool IsMacro = isa<const MacroInfo *>(Key);
261
262 // Decompose the location for the declaration and find the beginning of the
263 // file buffer.
264 const FileIDAndOffset LocDecomp =
265 SourceMgr.getDecomposedLoc(RepresentativeLoc);
266
267 // Slow path.
268 auto OffsetCommentBehindDecl =
269 CommentsInTheFile.lower_bound(LocDecomp.second);
270
271 // First check whether we have a trailing comment.
272 if (OffsetCommentBehindDecl != CommentsInTheFile.end()) {
273 RawComment *CommentBehindDecl = OffsetCommentBehindDecl->second;
274 if ((CommentBehindDecl->isDocumentation() ||
275 LangOpts.CommentOpts.ParseAllComments) &&
276 CommentBehindDecl->isTrailingComment() &&
277 (IsMacro || (D && (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) ||
279 isa<ObjCPropertyDecl>(D))))) {
280
281 // Check that Doxygen trailing comment comes after the declaration, starts
282 // on the same line and in the same file as the declaration.
283 if (SourceMgr.getLineNumber(LocDecomp.first, LocDecomp.second) ==
284 Comments.getCommentBeginLine(CommentBehindDecl, LocDecomp.first,
285 OffsetCommentBehindDecl->first)) {
286 return CommentBehindDecl;
287 }
288 }
289 }
290
291 // The comment just after the declaration was not a trailing comment.
292 // Let's look at the previous comment.
293 if (OffsetCommentBehindDecl == CommentsInTheFile.begin())
294 return nullptr;
295
296 auto OffsetCommentBeforeDecl = --OffsetCommentBehindDecl;
297 RawComment *CommentBeforeDecl = OffsetCommentBeforeDecl->second;
298
299 // Check that we actually have a non-member Doxygen comment.
300 if (!(CommentBeforeDecl->isDocumentation() ||
301 LangOpts.CommentOpts.ParseAllComments) ||
302 CommentBeforeDecl->isTrailingComment())
303 return nullptr;
304
305 // Decompose the end of the comment.
306 const unsigned CommentEndOffset =
307 Comments.getCommentEndOffset(CommentBeforeDecl);
308 if (CommentEndOffset > LocDecomp.second)
309 return nullptr;
310
311 // Get the corresponding buffer.
312 bool Invalid = false;
313 const char *Buffer =
314 SourceMgr.getBufferData(LocDecomp.first, &Invalid).data();
315 if (Invalid)
316 return nullptr;
317
318 // Extract text between the comment and declaration.
319 StringRef Text(Buffer + CommentEndOffset,
320 LocDecomp.second - CommentEndOffset);
321
322 // There should be no other declarations or preprocessor directives between
323 // comment and declaration.
324 if (Text.find_last_of(";{}#@") != StringRef::npos)
325 return nullptr;
326
327 return CommentBeforeDecl;
328}
329
331 const auto Locs = getLocsForCommentSearch(Key, SourceMgr);
332
333 for (const auto Loc : Locs) {
334 // If the declaration or macro doesn't map directly to a location in a file,
335 // we can't find the comment.
336 if (Loc.isInvalid() || !Loc.isFileID())
337 continue;
338
340 ExternalSource->ReadComments();
341 CommentsLoaded = true;
342 }
343
344 if (Comments.empty())
345 continue;
346
347 const FileID File = SourceMgr.getDecomposedLoc(Loc).first;
348 if (!File.isValid())
349 continue;
350
351 const auto CommentsInThisFile = Comments.getCommentsInFile(File);
352 if (!CommentsInThisFile || CommentsInThisFile->empty())
353 continue;
354
355 if (RawComment *Comment =
356 getRawCommentNoCacheImpl(Key, Loc, *CommentsInThisFile))
357 return Comment;
358 }
359
360 return nullptr;
361}
362
364 assert(LangOpts.CommentOpts.RetainCommentsFromSystemHeaders ||
365 !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin()));
366 Comments.addComment(RC, LangOpts.CommentOpts, BumpAlloc);
367}
368
369const RawComment *
371 const Decl **OriginalDecl) const {
372 if (Key.isNull()) {
373 if (OriginalDecl)
374 *OriginalDecl = nullptr;
375 return nullptr;
376 }
377
378 // Macros have no redeclaration chain: look up directly, populate the cache,
379 // and return.
380 if (const auto *MI = dyn_cast<const MacroInfo *>(Key)) {
381 if (OriginalDecl)
382 *OriginalDecl = nullptr;
383 auto Existing = RawComments.find(Key);
384 if (Existing != RawComments.end())
385 return Existing->second;
386 if (const RawComment *RC = getRawCommentNoCache(Key)) {
387 cacheRawComment(MI, *RC);
388 return RC;
389 }
390 return nullptr;
391 }
392
393 const Decl *D = cast<const Decl *>(Key);
394 D = &adjustDeclToTemplate(*D);
395
396 // Any comment directly attached to D?
397 {
398 auto DeclComment = RawComments.find(D);
399 if (DeclComment != RawComments.end()) {
400 if (OriginalDecl)
401 *OriginalDecl = D;
402 return DeclComment->second;
403 }
404 }
405
406 // Any comment attached to any redeclaration of D?
407 const Decl *CanonicalD = D->getCanonicalDecl();
408 if (!CanonicalD)
409 return nullptr;
410
411 {
412 auto RedeclComment = RedeclChainComments.find(CanonicalD);
413 if (RedeclComment != RedeclChainComments.end()) {
414 if (OriginalDecl)
415 *OriginalDecl = RedeclComment->second;
416 auto CommentAtRedecl = RawComments.find(RedeclComment->second);
417 assert(CommentAtRedecl != RawComments.end() &&
418 "This decl is supposed to have comment attached.");
419 return CommentAtRedecl->second;
420 }
421 }
422
423 // Any redeclarations of D that we haven't checked for comments yet?
424 const Decl *LastCheckedRedecl = [&]() {
425 const Decl *LastChecked = CommentlessRedeclChains.lookup(CanonicalD);
426 bool CanUseCommentlessCache = false;
427 if (LastChecked) {
428 for (auto *Redecl : CanonicalD->redecls()) {
429 if (Redecl == D) {
430 CanUseCommentlessCache = true;
431 break;
432 }
433 if (Redecl == LastChecked)
434 break;
435 }
436 }
437 // FIXME: This could be improved so that even if CanUseCommentlessCache
438 // is false, once we've traversed past CanonicalD we still skip ahead
439 // LastChecked.
440 return CanUseCommentlessCache ? LastChecked : nullptr;
441 }();
442
443 for (const Decl *Redecl : D->redecls()) {
444 assert(Redecl);
445 // Skip all redeclarations that have been checked previously.
446 if (LastCheckedRedecl) {
447 if (LastCheckedRedecl == Redecl) {
448 LastCheckedRedecl = nullptr;
449 }
450 continue;
451 }
452 const RawComment *RedeclComment = getRawCommentNoCache(Redecl);
453 if (RedeclComment) {
454 cacheRawComment(Redecl, *RedeclComment);
455 if (OriginalDecl)
456 *OriginalDecl = Redecl;
457 return RedeclComment;
458 }
459 CommentlessRedeclChains[CanonicalD] = Redecl;
460 }
461
462 if (OriginalDecl)
463 *OriginalDecl = nullptr;
464 return nullptr;
465}
466
468 const RawComment &Comment) const {
469 assert(Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
470 RawComments.try_emplace(Original, &Comment);
471 if (const auto *D = dyn_cast<const Decl *>(Original)) {
472 const Decl *const CanonicalDecl = D->getCanonicalDecl();
473 RedeclChainComments.try_emplace(CanonicalDecl, D);
474 CommentlessRedeclChains.erase(CanonicalDecl);
475 }
476}
477
478static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
480 const DeclContext *DC = ObjCMethod->getDeclContext();
481 if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) {
482 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
483 if (!ID)
484 return;
485 // Add redeclared method here.
486 for (const auto *Ext : ID->known_extensions()) {
487 if (ObjCMethodDecl *RedeclaredMethod =
488 Ext->getMethod(ObjCMethod->getSelector(),
489 ObjCMethod->isInstanceMethod()))
490 Redeclared.push_back(RedeclaredMethod);
491 }
492 }
493}
494
496 const Preprocessor *PP) {
497 if (Comments.empty() || Decls.empty())
498 return;
499
500 FileID File;
501 for (const Decl *D : Decls) {
502 if (D->isInvalidDecl())
503 continue;
504
505 D = &adjustDeclToTemplate(*D);
506 SourceLocation Loc = D->getLocation();
507 if (Loc.isValid()) {
508 // See if there are any new comments that are not attached to a decl.
509 // The location doesn't have to be precise - we care only about the file.
510 File = SourceMgr.getDecomposedLoc(Loc).first;
511 break;
512 }
513 }
514
515 if (File.isInvalid())
516 return;
517
518 auto CommentsInThisFile = Comments.getCommentsInFile(File);
519 if (!CommentsInThisFile || CommentsInThisFile->empty() ||
520 CommentsInThisFile->rbegin()->second->isAttached())
521 return;
522
523 // There is at least one comment not attached to a decl.
524 // Maybe it should be attached to one of Decls?
525 //
526 // Note that this way we pick up not only comments that precede the
527 // declaration, but also comments that *follow* the declaration -- thanks to
528 // the lookahead in the lexer: we've consumed the semicolon and looked
529 // ahead through comments.
530 for (const Decl *D : Decls) {
531 assert(D);
532 if (D->isInvalidDecl())
533 continue;
534
535 D = &adjustDeclToTemplate(*D);
536
537 if (RawComments.count(D) > 0)
538 continue;
539
540 const auto DeclLocs = getLocsForCommentSearch(D, SourceMgr);
541
542 for (const auto DeclLoc : DeclLocs) {
543 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
544 continue;
545
546 const FileID DeclFile = SourceMgr.getDecomposedLoc(DeclLoc).first;
547 if (!DeclFile.isValid())
548 continue;
549
550 const auto *CommentsInDeclFile =
551 DeclFile == File ? CommentsInThisFile
552 : Comments.getCommentsInFile(DeclFile);
553 if (!CommentsInDeclFile || CommentsInDeclFile->empty())
554 continue;
555
556 if (RawComment *const DocComment =
557 getRawCommentNoCacheImpl(D, DeclLoc, *CommentsInDeclFile)) {
558 cacheRawComment(D, *DocComment);
559 comments::FullComment *FC = DocComment->parse(*this, PP, D);
560 ParsedComments[D->getCanonicalDecl()] = FC;
561 break;
562 }
563 }
564 }
565}
566
568 const Decl *D) const {
569 auto *ThisDeclInfo = new (*this) comments::DeclInfo;
570 ThisDeclInfo->CommentDecl = D;
571 ThisDeclInfo->IsFilled = false;
572 ThisDeclInfo->fill();
573 ThisDeclInfo->CommentDecl = FC->getDecl();
574 if (!ThisDeclInfo->TemplateParameters)
575 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
577 new (*this) comments::FullComment(FC->getBlocks(),
578 ThisDeclInfo);
579 return CFC;
580}
581
583 const RawComment *RC = getRawCommentNoCache(D);
584 return RC ? RC->parse(*this, nullptr, D) : nullptr;
585}
586
588 const Decl *D,
589 const Preprocessor *PP) const {
590 if (!D || D->isInvalidDecl())
591 return nullptr;
592 D = &adjustDeclToTemplate(*D);
593
594 const Decl *Canonical = D->getCanonicalDecl();
595 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
596 ParsedComments.find(Canonical);
597
598 if (Pos != ParsedComments.end()) {
599 if (Canonical != D) {
600 comments::FullComment *FC = Pos->second;
602 return CFC;
603 }
604 return Pos->second;
605 }
606
607 const Decl *OriginalDecl = nullptr;
608
609 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
610 if (!RC) {
613 const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
614 if (OMD && OMD->isPropertyAccessor())
615 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
616 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
617 return cloneFullComment(FC, D);
618 if (OMD)
619 addRedeclaredMethods(OMD, Overridden);
620 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
621 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
622 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
623 return cloneFullComment(FC, D);
624 }
625 else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
626 // Attach any tag type's documentation to its typedef if latter
627 // does not have one of its own.
628 QualType QT = TD->getUnderlyingType();
629 if (const auto *TT = QT->getAs<TagType>())
630 if (comments::FullComment *FC = getCommentForDecl(TT->getDecl(), PP))
631 return cloneFullComment(FC, D);
632 }
633 else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
634 while (IC->getSuperClass()) {
635 IC = IC->getSuperClass();
637 return cloneFullComment(FC, D);
638 }
639 }
640 else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) {
641 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
643 return cloneFullComment(FC, D);
644 }
645 else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
646 if (!(RD = RD->getDefinition()))
647 return nullptr;
648 // Check non-virtual bases.
649 for (const auto &I : RD->bases()) {
650 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
651 continue;
652 QualType Ty = I.getType();
653 if (Ty.isNull())
654 continue;
656 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
657 continue;
658
660 return cloneFullComment(FC, D);
661 }
662 }
663 // Check virtual bases.
664 for (const auto &I : RD->vbases()) {
665 if (I.getAccessSpecifier() != AS_public)
666 continue;
667 QualType Ty = I.getType();
668 if (Ty.isNull())
669 continue;
670 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
671 if (!(VirtualBase= VirtualBase->getDefinition()))
672 continue;
674 return cloneFullComment(FC, D);
675 }
676 }
677 }
678 return nullptr;
679 }
680
681 // If the RawComment was attached to other redeclaration of this Decl, we
682 // should parse the comment in context of that other Decl. This is important
683 // because comments can contain references to parameter names which can be
684 // different across redeclarations.
685 if (D != OriginalDecl && OriginalDecl)
686 return getCommentForDecl(OriginalDecl, PP);
687
688 comments::FullComment *FC = RC->parse(*this, PP, D);
689 ParsedComments[Canonical] = FC;
690 return FC;
691}
692
693void ASTContext::CanonicalTemplateTemplateParm::Profile(
694 llvm::FoldingSetNodeID &ID, const ASTContext &C,
696 ID.AddInteger(Parm->getDepth());
697 ID.AddInteger(Parm->getPosition());
698 ID.AddBoolean(Parm->isParameterPack());
699 ID.AddInteger(Parm->templateParameterKind());
700
702 ID.AddInteger(Params->size());
704 PEnd = Params->end();
705 P != PEnd; ++P) {
706 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
707 ID.AddInteger(0);
708 ID.AddBoolean(TTP->isParameterPack());
709 ID.AddInteger(
710 TTP->getNumExpansionParameters().toInternalRepresentation());
711 continue;
712 }
713
714 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
715 ID.AddInteger(1);
716 ID.AddBoolean(NTTP->isParameterPack());
717 ID.AddPointer(C.getUnconstrainedType(C.getCanonicalType(NTTP->getType()))
718 .getAsOpaquePtr());
719 if (NTTP->isExpandedParameterPack()) {
720 ID.AddBoolean(true);
721 ID.AddInteger(NTTP->getNumExpansionTypes());
722 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
723 QualType T = NTTP->getExpansionType(I);
724 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
725 }
726 } else
727 ID.AddBoolean(false);
728 continue;
729 }
730
731 auto *TTP = cast<TemplateTemplateParmDecl>(*P);
732 ID.AddInteger(2);
733 Profile(ID, C, TTP);
734 }
735}
736
737TemplateTemplateParmDecl *
739 TemplateTemplateParmDecl *TTP) const {
740 // Check if we already have a canonical template template parameter.
741 llvm::FoldingSetNodeID ID;
742 CanonicalTemplateTemplateParm::Profile(ID, *this, TTP);
743 llvm::FoldingSetInsertToken Token;
744 CanonicalTemplateTemplateParm *Canonical =
745 CanonTemplateTemplateParms.lookup(ID, Token);
746 if (Canonical)
747 return Canonical->getParam();
748
749 // Build a canonical template parameter list.
751 SmallVector<NamedDecl *, 4> CanonParams;
752 CanonParams.reserve(Params->size());
754 PEnd = Params->end();
755 P != PEnd; ++P) {
756 // Note that, per C++20 [temp.over.link]/6, when determining whether
757 // template-parameters are equivalent, constraints are ignored.
758 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
761 TTP->getDepth(), TTP->getIndex(), nullptr, false,
762 TTP->isParameterPack(), /*HasTypeConstraint=*/false,
763 TTP->getNumExpansionParameters());
764 CanonParams.push_back(NewTTP);
765 } else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
769 if (NTTP->isExpandedParameterPack()) {
770 SmallVector<QualType, 2> ExpandedTypes;
772 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
773 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
774 ExpandedTInfos.push_back(
775 getTrivialTypeSourceInfo(ExpandedTypes.back()));
776 }
777
781 NTTP->getDepth(),
782 NTTP->getPosition(), nullptr,
783 T,
784 TInfo,
785 ExpandedTypes,
786 ExpandedTInfos);
787 } else {
791 NTTP->getDepth(),
792 NTTP->getPosition(), nullptr,
793 T,
794 NTTP->isParameterPack(),
795 TInfo);
796 }
797 CanonParams.push_back(Param);
798 } else
799 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
801 }
802
805 TTP->getPosition(), TTP->isParameterPack(), nullptr,
807 /*Typename=*/false,
809 CanonParams, SourceLocation(),
810 /*RequiresClause=*/nullptr));
811
812 // Get the new insert position for the node we care about.
813 Canonical = CanonTemplateTemplateParms.lookup(ID, Token);
814 assert(!Canonical && "Shouldn't be in the map!");
815 (void)Canonical;
816
817 // Create the canonical template template parameter entry.
818 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
819 CanonTemplateTemplateParms.insert(Canonical, Token);
820 return CanonTTP;
821}
822
825 TemplateTemplateParmDecl *TTP) const {
826 llvm::FoldingSetNodeID ID;
827 CanonicalTemplateTemplateParm::Profile(ID, *this, TTP);
828 llvm::FoldingSetInsertToken Token;
829 CanonicalTemplateTemplateParm *Canonical =
830 CanonTemplateTemplateParms.lookup(ID, Token);
831 return Canonical ? Canonical->getParam() : nullptr;
832}
833
836 TemplateTemplateParmDecl *CanonTTP) const {
837 llvm::FoldingSetNodeID ID;
838 CanonicalTemplateTemplateParm::Profile(ID, *this, CanonTTP);
839 llvm::FoldingSetInsertToken Token;
840 if (auto *Existing = CanonTemplateTemplateParms.lookup(ID, Token))
841 return Existing->getParam();
842 CanonTemplateTemplateParms.insert(
843 new (*this) CanonicalTemplateTemplateParm(CanonTTP), Token);
844 return CanonTTP;
845}
846
847/// For the purposes of overflow pattern exclusion, does this match the
848/// while(i--) pattern?
849static bool matchesPostDecrInWhile(const UnaryOperator *UO, ASTContext &Ctx) {
850 if (UO->getOpcode() != UO_PostDec)
851 return false;
852
853 if (!UO->getType()->isUnsignedIntegerType())
854 return false;
855
856 // -fsanitize-undefined-ignore-overflow-pattern=unsigned-post-decr-while
859 return false;
860
861 // all Parents (usually just one) must be a WhileStmt
862 return llvm::all_of(
864 [](const DynTypedNode &P) { return P.get<WhileStmt>() != nullptr; });
865}
866
868 // -fsanitize-undefined-ignore-overflow-pattern=negated-unsigned-const
869 // ... like -1UL;
870 if (UO->getOpcode() == UO_Minus &&
871 getLangOpts().isOverflowPatternExcluded(
873 UO->isIntegerConstantExpr(*this)) {
874 return true;
875 }
876
877 if (matchesPostDecrInWhile(UO, *this))
878 return true;
879
880 return false;
881}
882
883/// Check if a type can have its sanitizer instrumentation elided based on its
884/// presence within an ignorelist.
886 const QualType &Ty) const {
887 std::string TyName = Ty.getUnqualifiedType().getAsString(getPrintingPolicy());
888 return NoSanitizeL->containsType(Mask, TyName);
889}
890
892 auto Kind = getTargetInfo().getCXXABI().getKind();
893 return getLangOpts().CXXABI.value_or(Kind);
894}
895
896CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
897 if (!LangOpts.CPlusPlus) return nullptr;
898
899 switch (getCXXABIKind()) {
900 case TargetCXXABI::AppleARM64:
901 case TargetCXXABI::Fuchsia:
902 case TargetCXXABI::GenericARM: // Same as Itanium at this level
903 case TargetCXXABI::iOS:
904 case TargetCXXABI::WatchOS:
905 case TargetCXXABI::GenericAArch64:
906 case TargetCXXABI::GenericMIPS:
907 case TargetCXXABI::GenericItanium:
908 case TargetCXXABI::WebAssembly:
909 case TargetCXXABI::XL:
910 return CreateItaniumCXXABI(*this);
911 case TargetCXXABI::Microsoft:
912 return CreateMicrosoftCXXABI(*this);
913 }
914 llvm_unreachable("Invalid CXXABI type!");
915}
916
918 if (!InterpContext) {
919 InterpContext.reset(new interp::Context(const_cast<ASTContext &>(*this)));
920 }
921 return *InterpContext;
922}
923
925 const LangOptions &LangOpts) {
926 switch (LangOpts.getAddressSpaceMapMangling()) {
928 return TI.useAddressSpaceMapMangling();
930 return true;
932 return false;
933 }
934 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
935}
936
938 IdentifierTable &idents, SelectorTable &sels,
940 : ConstantArrayTypes(this_(), ConstantArrayTypesLog2InitSize),
941 DependentSizedArrayTypes(this_()), DependentSizedExtVectorTypes(this_()),
942 DependentAddressSpaceTypes(this_()), DependentVectorTypes(this_()),
943 DependentSizedMatrixTypes(this_()),
944 FunctionProtoTypes(this_(), FunctionProtoTypesLog2InitSize),
945 DependentTypeOfExprTypes(this_()), DependentDecltypeTypes(this_()),
946 DependentPackIndexingTypes(this_()), TemplateSpecializationTypes(this_()),
947 AttributedTypes(this_()), DependentBitIntTypes(this_()),
948 HLSLAttributedResourceTypes(this_()),
949 SubstTemplateTemplateParmPacks(this_()), DeducedTemplates(this_()),
950 PackIndexingTemplates(this_()), ArrayParameterTypes(this_()),
951 CanonTemplateTemplateParms(this_()), SourceMgr(SM), LangOpts(LOpts),
952 NoSanitizeL(new NoSanitizeList(LangOpts.NoSanitizeFiles, SM)),
953 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
954 LangOpts.XRayNeverInstrumentFiles,
955 LangOpts.XRayAttrListFiles, SM)),
956 ProfList(new ProfileList(LangOpts.ProfileListFiles, SM)),
957 PrintingPolicy(LOpts), ParentMapCtx(new ParentMapContext(*this)),
958 Idents(idents), Selectors(sels), BuiltinInfo(builtins), TUKind(TUKind),
959 DeclarationNames(*this), Comments(SM),
960 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
961 CompCategories(this_()), LastSDM(nullptr, 0) {
963}
964
966 // Release the DenseMaps associated with DeclContext objects.
967 // FIXME: Is this the ideal solution?
968 ReleaseDeclContextMaps();
969
970 // Call all of the deallocation functions on all of their targets.
971 for (auto &Pair : Deallocations)
972 (Pair.first)(Pair.second);
973 Deallocations.clear();
974
975 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
976 // because they can contain DenseMaps.
977 for (llvm::DenseMap<const ObjCInterfaceDecl *,
979 I = ObjCLayouts.begin(),
980 E = ObjCLayouts.end();
981 I != E;)
982 // Increment in loop to prevent using deallocated memory.
983 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
984 R->Destroy(*this);
985 ObjCLayouts.clear();
986
987 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
988 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
989 // Increment in loop to prevent using deallocated memory.
990 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
991 R->Destroy(*this);
992 }
993 ASTRecordLayouts.clear();
994
995 CtorClosureDefaultArgs.clear();
996
997 for (const auto &Value : ModuleInitializers)
998 Value.second->~PerModuleInitializers();
999 ModuleInitializers.clear();
1000
1001 TUDecl = nullptr;
1002 XRayFilter.reset();
1003 NoSanitizeL.reset();
1004}
1005
1007
1008void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
1009 TraversalScope = TopLevelDecls;
1011}
1012
1013void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const {
1014 Deallocations.push_back({Callback, Data});
1015}
1016
1017void
1021
1023 llvm::errs() << "\n*** AST Context Stats:\n";
1024 llvm::errs() << " " << Types.size() << " types total.\n";
1025
1026 unsigned counts[] = {
1027#define TYPE(Name, Parent) 0,
1028#define ABSTRACT_TYPE(Name, Parent)
1029#include "clang/AST/TypeNodes.inc"
1030 0 // Extra
1031 };
1032
1033 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
1034 Type *T = Types[i];
1035 counts[(unsigned)T->getTypeClass()]++;
1036 }
1037
1038 unsigned Idx = 0;
1039 unsigned TotalBytes = 0;
1040#define TYPE(Name, Parent) \
1041 if (counts[Idx]) \
1042 llvm::errs() << " " << counts[Idx] << " " << #Name \
1043 << " types, " << sizeof(Name##Type) << " each " \
1044 << "(" << counts[Idx] * sizeof(Name##Type) \
1045 << " bytes)\n"; \
1046 TotalBytes += counts[Idx] * sizeof(Name##Type); \
1047 ++Idx;
1048#define ABSTRACT_TYPE(Name, Parent)
1049#include "clang/AST/TypeNodes.inc"
1050
1051 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
1052
1053 // Implicit special member functions.
1054 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
1056 << " implicit default constructors created\n";
1057 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
1059 << " implicit copy constructors created\n";
1060 if (getLangOpts().CPlusPlus)
1061 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
1063 << " implicit move constructors created\n";
1064 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
1066 << " implicit copy assignment operators created\n";
1067 if (getLangOpts().CPlusPlus)
1068 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
1070 << " implicit move assignment operators created\n";
1071 llvm::errs() << NumImplicitDestructorsDeclared << "/"
1073 << " implicit destructors created\n";
1074
1075 if (ExternalSource) {
1076 llvm::errs() << "\n";
1077 ExternalSource->PrintStats();
1078 }
1079
1080 BumpAlloc.PrintStats();
1081}
1082
1084 bool NotifyListeners) {
1085 if (NotifyListeners)
1086 if (auto *Listener = getASTMutationListener();
1088 Listener->RedefinedHiddenDefinition(ND, M);
1089
1090 MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M);
1091}
1092
1094 auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl()));
1095 if (It == MergedDefModules.end())
1096 return;
1097
1098 auto &Merged = It->second;
1099 llvm::DenseSet<Module*> Found;
1100 for (Module *&M : Merged)
1101 if (!Found.insert(M).second)
1102 M = nullptr;
1103 llvm::erase(Merged, nullptr);
1104}
1105
1108 auto MergedIt =
1109 MergedDefModules.find(cast<NamedDecl>(Def->getCanonicalDecl()));
1110 if (MergedIt == MergedDefModules.end())
1111 return {};
1112 return MergedIt->second;
1113}
1114
1115void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
1116 if (LazyInitializers.empty())
1117 return;
1118
1119 auto *Source = Ctx.getExternalSource();
1120 assert(Source && "lazy initializers but no external source");
1121
1122 auto LazyInits = std::move(LazyInitializers);
1123 LazyInitializers.clear();
1124
1125 for (auto ID : LazyInits)
1126 Initializers.push_back(Source->GetExternalDecl(ID));
1127
1128 assert(LazyInitializers.empty() &&
1129 "GetExternalDecl for lazy module initializer added more inits");
1130}
1131
1133 // One special case: if we add a module initializer that imports another
1134 // module, and that module's only initializer is an ImportDecl, simplify.
1135 if (const auto *ID = dyn_cast<ImportDecl>(D)) {
1136 auto It = ModuleInitializers.find(ID->getImportedModule());
1137
1138 // Maybe the ImportDecl does nothing at all. (Common case.)
1139 if (It == ModuleInitializers.end())
1140 return;
1141
1142 // Maybe the ImportDecl only imports another ImportDecl.
1143 auto &Imported = *It->second;
1144 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
1145 Imported.resolve(*this);
1146 auto *OnlyDecl = Imported.Initializers.front();
1147 if (isa<ImportDecl>(OnlyDecl))
1148 D = OnlyDecl;
1149 }
1150 }
1151
1152 auto *&Inits = ModuleInitializers[M];
1153 if (!Inits)
1154 Inits = new (*this) PerModuleInitializers;
1155 Inits->Initializers.push_back(D);
1156}
1157
1160 auto *&Inits = ModuleInitializers[M];
1161 if (!Inits)
1162 Inits = new (*this) PerModuleInitializers;
1163 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
1164 IDs.begin(), IDs.end());
1165}
1166
1168 auto It = ModuleInitializers.find(M);
1169 if (It == ModuleInitializers.end())
1170 return {};
1171
1172 auto *Inits = It->second;
1173 Inits->resolve(*this);
1174 return Inits->Initializers;
1175}
1176
1178 assert(M->isNamedModule());
1179 assert(!CurrentCXXNamedModule &&
1180 "We should set named module for ASTContext for only once");
1181 CurrentCXXNamedModule = M;
1182}
1183
1184bool ASTContext::isInSameModule(const Module *M1, const Module *M2) const {
1185 if (!M1 != !M2)
1186 return false;
1187
1188 /// Get the representative module for M. The representative module is the
1189 /// first module unit for a specific primary module name. So that the module
1190 /// units have the same representative module belongs to the same module.
1191 ///
1192 /// The process is helpful to reduce the expensive string operations.
1193 auto GetRepresentativeModule = [this](const Module *M) {
1194 auto Iter = SameModuleLookupSet.find(M);
1195 if (Iter != SameModuleLookupSet.end())
1196 return Iter->second;
1197
1198 const Module *RepresentativeModule =
1199 PrimaryModuleNameMap.try_emplace(M->getPrimaryModuleInterfaceName(), M)
1200 .first->second;
1201 SameModuleLookupSet[M] = RepresentativeModule;
1202 return RepresentativeModule;
1203 };
1204
1205 assert(M1 && "Shouldn't call `isInSameModule` if both M1 and M2 are none.");
1206 return GetRepresentativeModule(M1) == GetRepresentativeModule(M2);
1207}
1208
1210 if (!ExternCContext)
1211 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1212
1213 return ExternCContext;
1214}
1215
1226
1227#define BuiltinTemplate(BTName) \
1228 BuiltinTemplateDecl *ASTContext::get##BTName##Decl() const { \
1229 if (!Decl##BTName) \
1230 Decl##BTName = \
1231 buildBuiltinTemplateDecl(BTK##BTName, get##BTName##Name()); \
1232 return Decl##BTName; \
1233 }
1234#include "clang/Basic/BuiltinTemplates.inc"
1235
1237 RecordDecl::TagKind TK) const {
1238 SourceLocation Loc;
1239 RecordDecl *NewDecl;
1240 if (getLangOpts().CPlusPlus)
1241 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1242 Loc, &Idents.get(Name));
1243 else
1244 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1245 &Idents.get(Name));
1246 NewDecl->setImplicit();
1247 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1248 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
1249 return NewDecl;
1250}
1251
1253 StringRef Name) const {
1256 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1257 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1258 NewDecl->setImplicit();
1259 return NewDecl;
1260}
1261
1263 if (!Int128Decl)
1264 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
1265 return Int128Decl;
1266}
1267
1269 if (!UInt128Decl)
1270 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
1271 return UInt128Decl;
1272}
1273
1274void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
1275 auto *Ty = new (*this, alignof(BuiltinType)) BuiltinType(K);
1277 Types.push_back(Ty);
1278}
1279
1281 const TargetInfo *AuxTarget) {
1282 assert((!this->Target || this->Target == &Target) &&
1283 "Incorrect target reinitialization");
1284 assert(VoidTy.isNull() && "Context reinitialized?");
1285
1286 this->Target = &Target;
1287 this->AuxTarget = AuxTarget;
1288
1289 ABI.reset(createCXXABI(Target));
1290 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
1291
1292 // C99 6.2.5p19.
1293 InitBuiltinType(VoidTy, BuiltinType::Void);
1294
1295 // C99 6.2.5p2.
1296 InitBuiltinType(BoolTy, BuiltinType::Bool);
1297 // C99 6.2.5p3.
1298 if (LangOpts.CharIsSigned)
1299 InitBuiltinType(CharTy, BuiltinType::Char_S);
1300 else
1301 InitBuiltinType(CharTy, BuiltinType::Char_U);
1302 // C99 6.2.5p4.
1303 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1304 InitBuiltinType(ShortTy, BuiltinType::Short);
1305 InitBuiltinType(IntTy, BuiltinType::Int);
1306 InitBuiltinType(LongTy, BuiltinType::Long);
1307 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
1308
1309 // C99 6.2.5p6.
1310 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1311 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1312 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1313 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1314 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
1315
1316 // C99 6.2.5p10.
1317 InitBuiltinType(FloatTy, BuiltinType::Float);
1318 InitBuiltinType(DoubleTy, BuiltinType::Double);
1319 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
1320
1321 // GNU extension, __float128 for IEEE quadruple precision
1322 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1323
1324 // __ibm128 for IBM extended precision
1325 InitBuiltinType(Ibm128Ty, BuiltinType::Ibm128);
1326
1327 // C11 extension ISO/IEC TS 18661-3
1328 InitBuiltinType(Float16Ty, BuiltinType::Float16);
1329
1330 // ISO/IEC JTC1 SC22 WG14 N1169 Extension
1331 InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum);
1332 InitBuiltinType(AccumTy, BuiltinType::Accum);
1333 InitBuiltinType(LongAccumTy, BuiltinType::LongAccum);
1334 InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum);
1335 InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum);
1336 InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum);
1337 InitBuiltinType(ShortFractTy, BuiltinType::ShortFract);
1338 InitBuiltinType(FractTy, BuiltinType::Fract);
1339 InitBuiltinType(LongFractTy, BuiltinType::LongFract);
1340 InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract);
1341 InitBuiltinType(UnsignedFractTy, BuiltinType::UFract);
1342 InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract);
1343 InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum);
1344 InitBuiltinType(SatAccumTy, BuiltinType::SatAccum);
1345 InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum);
1346 InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
1347 InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum);
1348 InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum);
1349 InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract);
1350 InitBuiltinType(SatFractTy, BuiltinType::SatFract);
1351 InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract);
1352 InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
1353 InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract);
1354 InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract);
1355
1356 // GNU extension, 128-bit integers.
1357 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1358 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1359
1360 // C++ 3.9.1p5
1361 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1362 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1363 else // -fshort-wchar makes wchar_t be unsigned.
1364 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1365 if (LangOpts.CPlusPlus && LangOpts.WChar)
1367 else {
1368 // C99 (or C++ using -fno-wchar).
1369 WideCharTy = getFromTargetType(Target.getWCharType());
1370 }
1371
1372 WIntTy = getFromTargetType(Target.getWIntType());
1373
1374 // C++20 (proposed)
1375 InitBuiltinType(Char8Ty, BuiltinType::Char8);
1376
1377 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1378 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1379 else // C99
1380 Char16Ty = getFromTargetType(Target.getChar16Type());
1381
1382 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1383 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1384 else // C99
1385 Char32Ty = getFromTargetType(Target.getChar32Type());
1386
1387 // Placeholder type for type-dependent expressions whose type is
1388 // completely unknown. No code should ever check a type against
1389 // DependentTy and users should never see it; however, it is here to
1390 // help diagnose failures to properly check for type-dependent
1391 // expressions.
1392 InitBuiltinType(DependentTy, BuiltinType::Dependent);
1393
1394 // Placeholder type for functions.
1395 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1396
1397 // Placeholder type for bound members.
1398 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1399
1400 // Placeholder type for unresolved templates.
1401 InitBuiltinType(UnresolvedTemplateTy, BuiltinType::UnresolvedTemplate);
1402
1403 // Placeholder type for pseudo-objects.
1404 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1405
1406 // "any" type; useful for debugger-like clients.
1407 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1408
1409 // Placeholder type for unbridged ARC casts.
1410 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1411
1412 // Placeholder type for builtin functions.
1413 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1414
1415 // Placeholder type for OMP array sections.
1416 if (LangOpts.OpenMP) {
1417 InitBuiltinType(ArraySectionTy, BuiltinType::ArraySection);
1418 InitBuiltinType(OMPArrayShapingTy, BuiltinType::OMPArrayShaping);
1419 InitBuiltinType(OMPIteratorTy, BuiltinType::OMPIterator);
1420 }
1421 // Placeholder type for OpenACC array sections, if we are ALSO in OMP mode,
1422 // don't bother, as we're just using the same type as OMP.
1423 if (LangOpts.OpenACC && !LangOpts.OpenMP) {
1424 InitBuiltinType(ArraySectionTy, BuiltinType::ArraySection);
1425 }
1426 if (LangOpts.MatrixTypes)
1427 InitBuiltinType(IncompleteMatrixIdxTy, BuiltinType::IncompleteMatrixIdx);
1428
1429 // Builtin types for 'id', 'Class', and 'SEL'.
1430 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1431 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
1432 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
1433
1434 if (LangOpts.OpenCL) {
1435#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1436 InitBuiltinType(SingletonId, BuiltinType::Id);
1437#include "clang/Basic/OpenCLImageTypes.def"
1438
1439 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
1440 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
1441 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1442 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1443 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
1444
1445#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1446 InitBuiltinType(Id##Ty, BuiltinType::Id);
1447#include "clang/Basic/OpenCLExtensionTypes.def"
1448 }
1449
1450 if (LangOpts.HLSL) {
1451#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
1452 InitBuiltinType(SingletonId, BuiltinType::Id);
1453#include "clang/Basic/HLSLIntangibleTypes.def"
1454
1455#define HLSL_PACKED_TYPE(Name, Id, SingletonId) \
1456 InitBuiltinType(SingletonId, BuiltinType::Id);
1457#include "clang/Basic/HLSLPackedTypes.def"
1458 }
1459
1460 if (Target.hasAArch64ACLETypes() ||
1461 (AuxTarget && AuxTarget->hasAArch64ACLETypes())) {
1462#define SVE_TYPE(Name, Id, SingletonId) \
1463 InitBuiltinType(SingletonId, BuiltinType::Id);
1464#include "clang/Basic/AArch64ACLETypes.def"
1465 }
1466
1467 if (Target.getTriple().isPPC64()) {
1468#define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
1469 InitBuiltinType(Id##Ty, BuiltinType::Id);
1470#include "clang/Basic/PPCTypes.def"
1471#define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
1472 InitBuiltinType(Id##Ty, BuiltinType::Id);
1473#include "clang/Basic/PPCTypes.def"
1474 }
1475
1476 if (Target.hasRISCVVTypes()) {
1477#define RVV_TYPE(Name, Id, SingletonId) \
1478 InitBuiltinType(SingletonId, BuiltinType::Id);
1479#include "clang/Basic/RISCVVTypes.def"
1480 }
1481
1482 if (Target.getTriple().isWasm() && Target.hasFeature("reference-types")) {
1483#define WASM_TYPE(Name, Id, SingletonId) \
1484 InitBuiltinType(SingletonId, BuiltinType::Id);
1485#include "clang/Basic/WebAssemblyReferenceTypes.def"
1486 }
1487
1488 if (Target.hasAMDGPUTypes() || (AuxTarget && (AuxTarget->hasAMDGPUTypes()))) {
1489#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) \
1490 InitBuiltinType(SingletonId, BuiltinType::Id);
1491#include "clang/Basic/AMDGPUTypes.def"
1492 }
1493
1494 if (Target.getTriple().isSPIRV() ||
1495 (AuxTarget && AuxTarget->getTriple().isSPIRV())) {
1496#define SPIRV_TYPE(Name, Id, SingletonId) \
1497 InitBuiltinType(SingletonId, BuiltinType::Id);
1498#include "clang/Basic/SPIRVTypes.def"
1499 }
1500
1501 // Builtin type for __objc_yes and __objc_no
1502 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1504
1505 ObjCConstantStringType = QualType();
1506
1507 ObjCSuperType = QualType();
1508
1509 // void * type
1510 if (LangOpts.OpenCLGenericAddressSpace) {
1511 auto Q = VoidTy.getQualifiers();
1512 Q.setAddressSpace(LangAS::opencl_generic);
1514 getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
1515 } else {
1517 }
1518
1519 // nullptr type (C++0x 2.14.7)
1520 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
1521
1522 // std::meta::info type (C++26 21.4.1)
1523 InitBuiltinType(MetaInfoTy, BuiltinType::MetaInfo);
1524
1525 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1526 InitBuiltinType(HalfTy, BuiltinType::Half);
1527
1528 InitBuiltinType(BFloat16Ty, BuiltinType::BFloat16);
1529
1530 // Builtin type used to help define __builtin_va_list.
1531 VaListTagDecl = nullptr;
1532
1533 // MSVC predeclares struct _GUID, and we need it to create MSGuidDecls.
1534 if (LangOpts.MicrosoftExt || LangOpts.Borland) {
1537 }
1538}
1539
1541 return SourceMgr.getDiagnostics();
1542}
1543
1545 return new (DeclAttrAllocator.Allocate()) AttrVec;
1546}
1547
1550 return CtorClosureDefaultArgs.lookup(CD);
1551}
1552
1555 assert(!CtorClosureDefaultArgs.contains(CD));
1556 CtorClosureDefaultArgs[CD] = Args;
1557}
1558
1561 auto It =
1562 ExplicitInstantiations.find(cast<NamedDecl>(Spec->getCanonicalDecl()));
1563 if (It != ExplicitInstantiations.end())
1564 return It->second;
1565 return {};
1566}
1567
1570 ExplicitInstantiations[cast<NamedDecl>(Spec->getCanonicalDecl())].push_back(
1571 EID);
1572}
1573
1576 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1577 TemplateOrInstantiation.find(Var);
1578 if (Pos == TemplateOrInstantiation.end())
1579 return {};
1580
1581 return Pos->second;
1582}
1583
1584void
1587 SourceLocation PointOfInstantiation) {
1588 assert(Inst->isStaticDataMember() && "Not a static data member");
1589 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1591 Tmpl, TSK, PointOfInstantiation));
1592}
1593
1594void
1597 assert(!TemplateOrInstantiation[Inst] &&
1598 "Already noted what the variable was instantiated from");
1599 TemplateOrInstantiation[Inst] = TSI;
1600}
1601
1602NamedDecl *
1604 return InstantiatedFromUsingDecl.lookup(UUD);
1605}
1606
1607void
1609 assert((isa<UsingDecl>(Pattern) ||
1612 "pattern decl is not a using decl");
1613 assert((isa<UsingDecl>(Inst) ||
1616 "instantiation did not produce a using decl");
1617 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1618 InstantiatedFromUsingDecl[Inst] = Pattern;
1619}
1620
1623 return InstantiatedFromUsingEnumDecl.lookup(UUD);
1624}
1625
1627 UsingEnumDecl *Pattern) {
1628 assert(!InstantiatedFromUsingEnumDecl[Inst] && "pattern already exists");
1629 InstantiatedFromUsingEnumDecl[Inst] = Pattern;
1630}
1631
1634 return InstantiatedFromUsingShadowDecl.lookup(Inst);
1635}
1636
1637void
1639 UsingShadowDecl *Pattern) {
1640 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1641 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1642}
1643
1644FieldDecl *
1646 return InstantiatedFromUnnamedFieldDecl.lookup(Field);
1647}
1648
1650 FieldDecl *Tmpl) {
1651 assert((!Inst->getDeclName() || Inst->isPlaceholderVar(getLangOpts())) &&
1652 "Instantiated field decl is not unnamed");
1653 assert((!Inst->getDeclName() || Inst->isPlaceholderVar(getLangOpts())) &&
1654 "Template field decl is not unnamed");
1655 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1656 "Already noted what unnamed field was instantiated from");
1657
1658 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1659}
1660
1665
1670
1671unsigned
1673 auto Range = overridden_methods(Method);
1674 return Range.end() - Range.begin();
1675}
1676
1679 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1680 OverriddenMethods.find(Method->getCanonicalDecl());
1681 if (Pos == OverriddenMethods.end())
1682 return overridden_method_range(nullptr, nullptr);
1683 return overridden_method_range(Pos->second.begin(), Pos->second.end());
1684}
1685
1687 const CXXMethodDecl *Overridden) {
1688 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1689 OverriddenMethods[Method].push_back(Overridden);
1690}
1691
1693 const NamedDecl *D,
1694 SmallVectorImpl<const NamedDecl *> &Overridden) const {
1695 assert(D);
1696
1697 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1698 Overridden.append(overridden_methods_begin(CXXMethod),
1699 overridden_methods_end(CXXMethod));
1700 return;
1701 }
1702
1703 const auto *Method = dyn_cast<ObjCMethodDecl>(D);
1704 if (!Method)
1705 return;
1706
1708 Method->getOverriddenMethods(OverDecls);
1709 Overridden.append(OverDecls.begin(), OverDecls.end());
1710}
1711
1712std::optional<ASTContext::CXXRecordDeclRelocationInfo>
1714 assert(RD);
1715 CXXRecordDecl *D = RD->getDefinition();
1716 auto it = RelocatableClasses.find(D);
1717 if (it != RelocatableClasses.end())
1718 return it->getSecond();
1719 return std::nullopt;
1720}
1721
1724 assert(RD);
1725 CXXRecordDecl *D = RD->getDefinition();
1726 assert(RelocatableClasses.find(D) == RelocatableClasses.end());
1727 RelocatableClasses.insert({D, Info});
1728}
1729
1731 const ASTContext &Context, const CXXRecordDecl *Class) {
1732 if (!Class->isPolymorphic())
1733 return false;
1734 const CXXRecordDecl *BaseType = Context.baseForVTableAuthentication(Class);
1735 using AuthAttr = VTablePointerAuthenticationAttr;
1736 const AuthAttr *ExplicitAuth = BaseType->getAttr<AuthAttr>();
1737 if (!ExplicitAuth)
1738 return Context.getLangOpts().PointerAuthVTPtrAddressDiscrimination;
1739 AuthAttr::AddressDiscriminationMode AddressDiscrimination =
1740 ExplicitAuth->getAddressDiscrimination();
1741 if (AddressDiscrimination == AuthAttr::DefaultAddressDiscrimination)
1742 return Context.getLangOpts().PointerAuthVTPtrAddressDiscrimination;
1743 return AddressDiscrimination == AuthAttr::AddressDiscrimination;
1744}
1745
1746ASTContext::PointerAuthContent
1747ASTContext::findPointerAuthContent(QualType T) const {
1748 assert(isPointerAuthenticationAvailable());
1749
1750 T = T.getCanonicalType();
1751 if (T->isDependentType())
1752 return PointerAuthContent::None;
1753
1754 if (T.hasAddressDiscriminatedPointerAuth())
1755 return PointerAuthContent::AddressDiscriminatedData;
1756 const RecordDecl *RD = T->getAsRecordDecl();
1757 if (!RD)
1758 return PointerAuthContent::None;
1759
1760 if (RD->isInvalidDecl())
1761 return PointerAuthContent::None;
1762
1763 if (auto Existing = RecordContainsAddressDiscriminatedPointerAuth.find(RD);
1764 Existing != RecordContainsAddressDiscriminatedPointerAuth.end())
1765 return Existing->second;
1766
1767 PointerAuthContent Result = PointerAuthContent::None;
1768
1769 auto SaveResultAndReturn = [&]() -> PointerAuthContent {
1770 auto [ResultIter, DidAdd] =
1771 RecordContainsAddressDiscriminatedPointerAuth.try_emplace(RD, Result);
1772 (void)ResultIter;
1773 (void)DidAdd;
1774 assert(DidAdd);
1775 return Result;
1776 };
1777 auto ShouldContinueAfterUpdate = [&](PointerAuthContent NewResult) {
1778 static_assert(PointerAuthContent::None <
1779 PointerAuthContent::AddressDiscriminatedVTable);
1780 static_assert(PointerAuthContent::AddressDiscriminatedVTable <
1781 PointerAuthContent::AddressDiscriminatedData);
1782 if (NewResult > Result)
1783 Result = NewResult;
1784 return Result != PointerAuthContent::AddressDiscriminatedData;
1785 };
1786 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1788 !ShouldContinueAfterUpdate(
1789 PointerAuthContent::AddressDiscriminatedVTable))
1790 return SaveResultAndReturn();
1791 for (auto Base : CXXRD->bases()) {
1792 if (!ShouldContinueAfterUpdate(findPointerAuthContent(Base.getType())))
1793 return SaveResultAndReturn();
1794 }
1795 }
1796 for (auto *FieldDecl : RD->fields()) {
1797 if (!ShouldContinueAfterUpdate(
1798 findPointerAuthContent(FieldDecl->getType())))
1799 return SaveResultAndReturn();
1800 }
1801 return SaveResultAndReturn();
1802}
1803
1805 assert(!Import->getNextLocalImport() &&
1806 "Import declaration already in the chain");
1807 assert(!Import->isFromASTFile() && "Non-local import declaration");
1808 if (!FirstLocalImport) {
1809 FirstLocalImport = Import;
1810 LastLocalImport = Import;
1811 return;
1812 }
1813
1814 LastLocalImport->setNextLocalImport(Import);
1815 LastLocalImport = Import;
1816}
1817
1818//===----------------------------------------------------------------------===//
1819// Type Sizing and Analysis
1820//===----------------------------------------------------------------------===//
1821
1822/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1823/// scalar floating point type.
1824const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1825 switch (T->castAs<BuiltinType>()->getKind()) {
1826 default:
1827 llvm_unreachable("Not a floating point type!");
1828 case BuiltinType::BFloat16:
1829 return Target->getBFloat16Format();
1830 case BuiltinType::Float16:
1831 return Target->getHalfFormat();
1832 case BuiltinType::Half:
1833 return Target->getHalfFormat();
1834 case BuiltinType::Float: return Target->getFloatFormat();
1835 case BuiltinType::Double: return Target->getDoubleFormat();
1836 case BuiltinType::Ibm128:
1837 return Target->getIbm128Format();
1838 case BuiltinType::LongDouble:
1839 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1840 return AuxTarget->getLongDoubleFormat();
1841 return Target->getLongDoubleFormat();
1842 case BuiltinType::Float128:
1843 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1844 return AuxTarget->getFloat128Format();
1845 return Target->getFloat128Format();
1846 }
1847}
1848
1849CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1850 unsigned Align = Target->getCharWidth();
1851
1852 const unsigned AlignFromAttr = D->getMaxAlignment();
1853 if (AlignFromAttr)
1854 Align = AlignFromAttr;
1855
1856 // __attribute__((aligned)) can increase or decrease alignment
1857 // *except* on a struct or struct member, where it only increases
1858 // alignment unless 'packed' is also specified.
1859 //
1860 // It is an error for alignas to decrease alignment, so we can
1861 // ignore that possibility; Sema should diagnose it.
1862 bool UseAlignAttrOnly;
1863 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D))
1864 UseAlignAttrOnly =
1865 FD->hasAttr<PackedAttr>() || FD->getParent()->hasAttr<PackedAttr>();
1866 else
1867 UseAlignAttrOnly = AlignFromAttr != 0;
1868 // If we're using the align attribute only, just ignore everything
1869 // else about the declaration and its type.
1870 if (UseAlignAttrOnly) {
1871 // do nothing
1872 } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
1873 QualType T = VD->getType();
1874 if (const auto *RT = T->getAs<ReferenceType>()) {
1875 if (ForAlignof)
1876 T = RT->getPointeeType();
1877 else
1878 T = getPointerType(RT->getPointeeType());
1879 }
1880 QualType BaseT = getBaseElementType(T);
1881 if (T->isFunctionType())
1882 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1883 else if (!BaseT->isIncompleteType()) {
1884 // Adjust alignments of declarations with array type by the
1885 // large-array alignment on the target.
1886 if (const ArrayType *arrayType = getAsArrayType(T)) {
1887 unsigned MinWidth = Target->getLargeArrayMinWidth();
1888 if (!ForAlignof && MinWidth) {
1890 Align = std::max(Align, Target->getLargeArrayAlign());
1893 Align = std::max(Align, Target->getLargeArrayAlign());
1894 }
1895 }
1896 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1897 if (BaseT.getQualifiers().hasUnaligned())
1898 Align = Target->getCharWidth();
1899 }
1900
1901 // Ensure minimum alignment for global variables.
1902 if (const auto *VD = dyn_cast<VarDecl>(D))
1903 if (VD->hasGlobalStorage() && !ForAlignof) {
1904 uint64_t TypeSize =
1905 !BaseT->isIncompleteType() ? getTypeSize(T.getTypePtr()) : 0;
1906 Align = std::max(Align, getMinGlobalAlignOfVar(TypeSize, VD));
1907 }
1908
1909 // Fields can be subject to extra alignment constraints, like if
1910 // the field is packed, the struct is packed, or the struct has a
1911 // a max-field-alignment constraint (#pragma pack). So calculate
1912 // the actual alignment of the field within the struct, and then
1913 // (as we're expected to) constrain that by the alignment of the type.
1914 if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
1915 const RecordDecl *Parent = Field->getParent();
1916 // We can only produce a sensible answer if the record is valid.
1917 if (!Parent->isInvalidDecl()) {
1918 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
1919
1920 // Start with the record's overall alignment.
1921 unsigned FieldAlign = toBits(Layout.getAlignment());
1922
1923 // Use the GCD of that and the offset within the record.
1924 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1925 if (Offset > 0) {
1926 // Alignment is always a power of 2, so the GCD will be a power of 2,
1927 // which means we get to do this crazy thing instead of Euclid's.
1928 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1929 if (LowBitOfOffset < FieldAlign)
1930 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1931 }
1932
1933 Align = std::min(Align, FieldAlign);
1934 }
1935 }
1936 }
1937
1938 // Some targets have hard limitation on the maximum requestable alignment in
1939 // aligned attribute for static variables.
1940 const unsigned MaxAlignedAttr = getTargetInfo().getMaxAlignedAttribute();
1941 const auto *VD = dyn_cast<VarDecl>(D);
1942 if (MaxAlignedAttr && VD && VD->getStorageClass() == SC_Static)
1943 Align = std::min(Align, MaxAlignedAttr);
1944
1945 return toCharUnitsFromBits(Align);
1946}
1947
1949 return toCharUnitsFromBits(Target->getExnObjectAlignment());
1950}
1951
1952// getTypeInfoDataSizeInChars - Return the size of a type, in
1953// chars. If the type is a record, its data size is returned. This is
1954// the size of the memcpy that's performed when assigning this type
1955// using a trivial copy/move assignment operator.
1958
1959 // In C++, objects can sometimes be allocated into the tail padding
1960 // of a base-class subobject. We decide whether that's possible
1961 // during class layout, so here we can just trust the layout results.
1962 if (getLangOpts().CPlusPlus) {
1963 if (const auto *RD = T->getAsCXXRecordDecl(); RD && !RD->isInvalidDecl()) {
1964 const ASTRecordLayout &layout = getASTRecordLayout(RD);
1965 Info.Width = layout.getDataSize();
1966 }
1967 }
1968
1969 return Info;
1970}
1971
1972/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1973/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1976 const ConstantArrayType *CAT) {
1977 TypeInfoChars EltInfo = Context.getTypeInfoInChars(CAT->getElementType());
1978 uint64_t Size = CAT->getZExtSize();
1979 assert((Size == 0 || static_cast<uint64_t>(EltInfo.Width.getQuantity()) <=
1980 (uint64_t)(-1)/Size) &&
1981 "Overflow in array type char size evaluation");
1982 uint64_t Width = EltInfo.Width.getQuantity() * Size;
1983 unsigned Align = EltInfo.Align.getQuantity();
1984 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1985 Context.getTargetInfo().getPointerWidth(LangAS::Default) == 64)
1986 Width = llvm::alignTo(Width, Align);
1989 EltInfo.AlignRequirement);
1990}
1991
1993 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
1994 return getConstantArrayInfoInChars(*this, CAT);
1995 TypeInfo Info = getTypeInfo(T);
1998}
1999
2003
2005 // HLSL doesn't promote all small integer types to int, it
2006 // just uses the rank-based promotion rules for all types.
2007 if (getLangOpts().HLSL)
2008 return false;
2009
2010 if (const auto *BT = T->getAs<BuiltinType>())
2011 switch (BT->getKind()) {
2012 case BuiltinType::Bool:
2013 case BuiltinType::Char_S:
2014 case BuiltinType::Char_U:
2015 case BuiltinType::SChar:
2016 case BuiltinType::UChar:
2017 case BuiltinType::Short:
2018 case BuiltinType::UShort:
2019 case BuiltinType::WChar_S:
2020 case BuiltinType::WChar_U:
2021 case BuiltinType::Char8:
2022 case BuiltinType::Char16:
2023 case BuiltinType::Char32:
2024 return true;
2025 default:
2026 return false;
2027 }
2028
2029 // Enumerated types are promotable to their compatible integer types
2030 // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
2031 if (const auto *ED = T->getAsEnumDecl()) {
2032 if (T->isDependentType() || ED->getPromotionType().isNull() ||
2033 ED->isScoped())
2034 return false;
2035
2036 return true;
2037 }
2038
2039 // OverflowBehaviorTypes are promotable if their underlying type is promotable
2040 if (const auto *OBT = T->getAs<OverflowBehaviorType>()) {
2041 return isPromotableIntegerType(OBT->getUnderlyingType());
2042 }
2043
2044 return false;
2045}
2046
2048 return getTypeInfo(T).isAlignRequired();
2049}
2050
2052 return isAlignmentRequired(T.getTypePtr());
2053}
2054
2056 bool NeedsPreferredAlignment) const {
2057 // An alignment on a typedef overrides anything else.
2058 if (const auto *TT = T->getAs<TypedefType>())
2059 if (unsigned Align = TT->getDecl()->getMaxAlignment())
2060 return Align;
2061
2062 // If we have an (array of) complete type, we're done.
2064 if (!T->isIncompleteType())
2065 return NeedsPreferredAlignment ? getPreferredTypeAlign(T) : getTypeAlign(T);
2066
2067 // If we had an array type, its element type might be a typedef
2068 // type with an alignment attribute.
2069 if (const auto *TT = T->getAs<TypedefType>())
2070 if (unsigned Align = TT->getDecl()->getMaxAlignment())
2071 return Align;
2072
2073 // Otherwise, see if the declaration of the type had an attribute.
2074 if (const auto *TD = T->getAsTagDecl())
2075 return TD->getMaxAlignment();
2076
2077 return 0;
2078}
2079
2081 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
2082 if (I != MemoizedTypeInfo.end())
2083 return I->second;
2084
2085 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
2086 TypeInfo TI = getTypeInfoImpl(T);
2087 MemoizedTypeInfo[T] = TI;
2088 return TI;
2089}
2090
2091/// getTypeInfoImpl - Return the size of the specified type, in bits. This
2092/// method does not work on incomplete types.
2093///
2094/// FIXME: Pointers into different addr spaces could have different sizes and
2095/// alignment requirements: getPointerInfo should take an AddrSpace, this
2096/// should take a QualType, &c.
2097TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
2098 uint64_t Width = 0;
2099 unsigned Align = 8;
2102 switch (T->getTypeClass()) {
2103#define TYPE(Class, Base)
2104#define ABSTRACT_TYPE(Class, Base)
2105#define NON_CANONICAL_TYPE(Class, Base)
2106#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2107#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
2108 case Type::Class: \
2109 assert(!T->isDependentType() && "should not see dependent types here"); \
2110 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
2111#include "clang/AST/TypeNodes.inc"
2112 llvm_unreachable("Should not see dependent types");
2113
2114 case Type::FunctionNoProto:
2115 case Type::FunctionProto:
2116 // GCC extension: alignof(function) = 32 bits
2117 Width = 0;
2118 Align = 32;
2119 break;
2120
2121 case Type::IncompleteArray:
2122 case Type::VariableArray:
2123 case Type::ConstantArray:
2124 case Type::ArrayParameter: {
2125 // Model non-constant sized arrays as size zero, but track the alignment.
2126 uint64_t Size = 0;
2127 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
2128 Size = CAT->getZExtSize();
2129
2130 TypeInfo EltInfo = getTypeInfo(cast<ArrayType>(T)->getElementType());
2131 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
2132 "Overflow in array type bit size evaluation");
2133 Width = EltInfo.Width * Size;
2134 Align = EltInfo.Align;
2135 AlignRequirement = EltInfo.AlignRequirement;
2136 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
2137 getTargetInfo().getPointerWidth(LangAS::Default) == 64)
2138 Width = llvm::alignTo(Width, Align);
2139 break;
2140 }
2141
2142 case Type::ExtVector:
2143 case Type::Vector: {
2144 const auto *VT = cast<VectorType>(T);
2145 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
2146 Width = VT->isPackedVectorBoolType(*this)
2147 ? VT->getNumElements()
2148 : EltInfo.Width * VT->getNumElements();
2149 // Enforce at least byte size and alignment.
2150 Width = std::max<unsigned>(8, Width);
2151 Align = std::max<unsigned>(
2152 8, Target->vectorsAreElementAligned() ? EltInfo.Width : Width);
2153
2154 // If the alignment is not a power of 2, round up to the next power of 2.
2155 // This happens for non-power-of-2 length vectors.
2156 if (Align & (Align-1)) {
2157 Align = llvm::bit_ceil(Align);
2158 Width = llvm::alignTo(Width, Align);
2159 }
2160 // Adjust the alignment based on the target max.
2161 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
2162 if (TargetVectorAlign && TargetVectorAlign < Align)
2163 Align = TargetVectorAlign;
2164 if (VT->getVectorKind() == VectorKind::SveFixedLengthData)
2165 // Adjust the alignment for fixed-length SVE vectors. This is important
2166 // for non-power-of-2 vector lengths.
2167 Align = 128;
2168 else if (VT->getVectorKind() == VectorKind::SveFixedLengthPredicate)
2169 // Adjust the alignment for fixed-length SVE predicates.
2170 Align = 16;
2171 else if (isRVVFixedLengthVectorKind(VT->getVectorKind()))
2172 // Adjust the alignment for fixed-length RVV vectors.
2173 Align = std::min<unsigned>(64, Width);
2174 // Vector types have their natural alignment resist reduction by
2175 // #pragma pack in MSVC record layout.
2176 AlignRequirement = AlignRequirementKind::ResistPragmaPack;
2177 break;
2178 }
2179
2180 case Type::ConstantMatrix: {
2181 const auto *MT = cast<ConstantMatrixType>(T);
2182 TypeInfo ElementInfo = getTypeInfo(MT->getElementType());
2183 // The internal layout of a matrix value is implementation defined.
2184 // Initially be ABI compatible with arrays with respect to alignment and
2185 // size.
2186 Width = ElementInfo.Width * MT->getNumRows() * MT->getNumColumns();
2187 Align = ElementInfo.Align;
2188 break;
2189 }
2190
2191 case Type::Builtin:
2192 switch (cast<BuiltinType>(T)->getKind()) {
2193 default: llvm_unreachable("Unknown builtin type!");
2194 case BuiltinType::Void:
2195 // GCC extension: alignof(void) = 8 bits.
2196 Width = 0;
2197 Align = 8;
2198 break;
2199 case BuiltinType::Bool:
2200 Width = Target->getBoolWidth();
2201 Align = Target->getBoolAlign();
2202 break;
2203 case BuiltinType::Char_S:
2204 case BuiltinType::Char_U:
2205 case BuiltinType::UChar:
2206 case BuiltinType::SChar:
2207 case BuiltinType::Char8:
2208 Width = Target->getCharWidth();
2209 Align = Target->getCharAlign();
2210 break;
2211 case BuiltinType::WChar_S:
2212 case BuiltinType::WChar_U:
2213 Width = Target->getWCharWidth();
2214 Align = Target->getWCharAlign();
2215 break;
2216 case BuiltinType::Char16:
2217 Width = Target->getChar16Width();
2218 Align = Target->getChar16Align();
2219 break;
2220 case BuiltinType::Char32:
2221 Width = Target->getChar32Width();
2222 Align = Target->getChar32Align();
2223 break;
2224 case BuiltinType::UShort:
2225 case BuiltinType::Short:
2226 Width = Target->getShortWidth();
2227 Align = Target->getShortAlign();
2228 break;
2229 case BuiltinType::UInt:
2230 case BuiltinType::Int:
2231 Width = Target->getIntWidth();
2232 Align = Target->getIntAlign();
2233 break;
2234 case BuiltinType::ULong:
2235 case BuiltinType::Long:
2236 Width = Target->getLongWidth();
2237 Align = Target->getLongAlign();
2238 break;
2239 case BuiltinType::ULongLong:
2240 case BuiltinType::LongLong:
2241 Width = Target->getLongLongWidth();
2242 Align = Target->getLongLongAlign();
2243 break;
2244 case BuiltinType::Int128:
2245 case BuiltinType::UInt128:
2246 Width = 128;
2247 Align = Target->getInt128Align();
2248 break;
2249 case BuiltinType::ShortAccum:
2250 case BuiltinType::UShortAccum:
2251 case BuiltinType::SatShortAccum:
2252 case BuiltinType::SatUShortAccum:
2253 Width = Target->getShortAccumWidth();
2254 Align = Target->getShortAccumAlign();
2255 break;
2256 case BuiltinType::Accum:
2257 case BuiltinType::UAccum:
2258 case BuiltinType::SatAccum:
2259 case BuiltinType::SatUAccum:
2260 Width = Target->getAccumWidth();
2261 Align = Target->getAccumAlign();
2262 break;
2263 case BuiltinType::LongAccum:
2264 case BuiltinType::ULongAccum:
2265 case BuiltinType::SatLongAccum:
2266 case BuiltinType::SatULongAccum:
2267 Width = Target->getLongAccumWidth();
2268 Align = Target->getLongAccumAlign();
2269 break;
2270 case BuiltinType::ShortFract:
2271 case BuiltinType::UShortFract:
2272 case BuiltinType::SatShortFract:
2273 case BuiltinType::SatUShortFract:
2274 Width = Target->getShortFractWidth();
2275 Align = Target->getShortFractAlign();
2276 break;
2277 case BuiltinType::Fract:
2278 case BuiltinType::UFract:
2279 case BuiltinType::SatFract:
2280 case BuiltinType::SatUFract:
2281 Width = Target->getFractWidth();
2282 Align = Target->getFractAlign();
2283 break;
2284 case BuiltinType::LongFract:
2285 case BuiltinType::ULongFract:
2286 case BuiltinType::SatLongFract:
2287 case BuiltinType::SatULongFract:
2288 Width = Target->getLongFractWidth();
2289 Align = Target->getLongFractAlign();
2290 break;
2291 case BuiltinType::BFloat16:
2292 if (Target->hasBFloat16Type()) {
2293 Width = Target->getBFloat16Width();
2294 Align = Target->getBFloat16Align();
2295 } else if ((getLangOpts().SYCLIsDevice ||
2296 (getLangOpts().OpenMP &&
2297 getLangOpts().OpenMPIsTargetDevice)) &&
2298 AuxTarget->hasBFloat16Type()) {
2299 Width = AuxTarget->getBFloat16Width();
2300 Align = AuxTarget->getBFloat16Align();
2301 }
2302 break;
2303 case BuiltinType::Float16:
2304 case BuiltinType::Half:
2305 if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
2306 !getLangOpts().OpenMPIsTargetDevice) {
2307 Width = Target->getHalfWidth();
2308 Align = Target->getHalfAlign();
2309 } else {
2310 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2311 "Expected OpenMP device compilation.");
2312 Width = AuxTarget->getHalfWidth();
2313 Align = AuxTarget->getHalfAlign();
2314 }
2315 break;
2316 case BuiltinType::Float:
2317 Width = Target->getFloatWidth();
2318 Align = Target->getFloatAlign();
2319 break;
2320 case BuiltinType::Double:
2321 Width = Target->getDoubleWidth();
2322 Align = Target->getDoubleAlign();
2323 break;
2324 case BuiltinType::Ibm128:
2325 Width = Target->getIbm128Width();
2326 Align = Target->getIbm128Align();
2327 break;
2328 case BuiltinType::LongDouble:
2329 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2330 (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() ||
2331 Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) {
2332 Width = AuxTarget->getLongDoubleWidth();
2333 Align = AuxTarget->getLongDoubleAlign();
2334 } else {
2335 Width = Target->getLongDoubleWidth();
2336 Align = Target->getLongDoubleAlign();
2337 }
2338 // x87 extended precision (fp80) has its natural alignment resist
2339 // reduction by #pragma pack in MSVC record layout.
2340 if (&Target->getLongDoubleFormat() == &llvm::APFloat::x87DoubleExtended())
2341 AlignRequirement = AlignRequirementKind::ResistPragmaPack;
2342 break;
2343 case BuiltinType::Float128:
2344 if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
2345 !getLangOpts().OpenMPIsTargetDevice) {
2346 Width = Target->getFloat128Width();
2347 Align = Target->getFloat128Align();
2348 } else {
2349 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2350 "Expected OpenMP device compilation.");
2351 Width = AuxTarget->getFloat128Width();
2352 Align = AuxTarget->getFloat128Align();
2353 }
2354 break;
2355 case BuiltinType::NullPtr:
2356 // C++ 3.9.1p11: sizeof(nullptr_t) == sizeof(void*)
2357 Width = Target->getPointerWidth(LangAS::Default);
2358 Align = Target->getPointerAlign(LangAS::Default);
2359 break;
2360 case BuiltinType::MetaInfo:
2361 // sizeof(std::meta::info) == sizeof(void*)
2362 Width = Target->getPointerWidth(LangAS::Default);
2363 // alignof(std::meta::info) == alignof(void*)
2364 Align = Target->getPointerAlign(LangAS::Default);
2365 break;
2366 case BuiltinType::ObjCId:
2367 case BuiltinType::ObjCClass:
2368 case BuiltinType::ObjCSel:
2369 Width = Target->getPointerWidth(LangAS::Default);
2370 Align = Target->getPointerAlign(LangAS::Default);
2371 break;
2372 case BuiltinType::OCLSampler:
2373 case BuiltinType::OCLEvent:
2374 case BuiltinType::OCLClkEvent:
2375 case BuiltinType::OCLQueue:
2376 case BuiltinType::OCLReserveID:
2377#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2378 case BuiltinType::Id:
2379#include "clang/Basic/OpenCLImageTypes.def"
2380#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2381 case BuiltinType::Id:
2382#include "clang/Basic/OpenCLExtensionTypes.def"
2383 AS = Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
2384 Width = Target->getPointerWidth(AS);
2385 Align = Target->getPointerAlign(AS);
2386 break;
2387 // The SVE types are effectively target-specific. The length of an
2388 // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple
2389 // of 128 bits. There is one predicate bit for each vector byte, so the
2390 // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits.
2391 //
2392 // Because the length is only known at runtime, we use a dummy value
2393 // of 0 for the static length. The alignment values are those defined
2394 // by the Procedure Call Standard for the Arm Architecture.
2395#define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId) \
2396 case BuiltinType::Id: \
2397 Width = 0; \
2398 Align = 128; \
2399 break;
2400#define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId) \
2401 case BuiltinType::Id: \
2402 Width = 0; \
2403 Align = 16; \
2404 break;
2405#define SVE_OPAQUE_TYPE(Name, MangledName, Id, SingletonId) \
2406 case BuiltinType::Id: \
2407 Width = 0; \
2408 Align = 16; \
2409 break;
2410#define SVE_SCALAR_TYPE(Name, MangledName, Id, SingletonId, Bits) \
2411 case BuiltinType::Id: \
2412 Width = Bits; \
2413 Align = Bits; \
2414 break;
2415#include "clang/Basic/AArch64ACLETypes.def"
2416#define PPC_VECTOR_TYPE(Name, Id, Size) \
2417 case BuiltinType::Id: \
2418 Width = Size; \
2419 Align = Size; \
2420 break;
2421#include "clang/Basic/PPCTypes.def"
2422#define RVV_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, NF, IsSigned, \
2423 IsFP, IsBF) \
2424 case BuiltinType::Id: \
2425 Width = 0; \
2426 Align = ElBits; \
2427 break;
2428#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, ElKind) \
2429 case BuiltinType::Id: \
2430 Width = 0; \
2431 Align = 8; \
2432 break;
2433#include "clang/Basic/RISCVVTypes.def"
2434#define WASM_TYPE(Name, Id, SingletonId) \
2435 case BuiltinType::Id: \
2436 Width = 0; \
2437 Align = 8; \
2438 break;
2439#include "clang/Basic/WebAssemblyReferenceTypes.def"
2440#define AMDGPU_TYPE(NAME, ID, SINGLETONID, WIDTH, ALIGN) \
2441 case BuiltinType::ID: \
2442 Width = WIDTH; \
2443 Align = ALIGN; \
2444 break;
2445#include "clang/Basic/AMDGPUTypes.def"
2446#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
2447#include "clang/Basic/HLSLIntangibleTypes.def"
2448 Width = Target->getPointerWidth(LangAS::Default);
2449 Align = Target->getPointerAlign(LangAS::Default);
2450 break;
2451#define HLSL_PACKED_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
2452#include "clang/Basic/HLSLPackedTypes.def"
2453 Width = 32;
2454 Align = 32;
2455 break;
2456#define SPIRV_TYPE(Name, Id, SingletonId) \
2457 case BuiltinType::Id: \
2458 Width = Target->getPointerWidth(LangAS::Default); \
2459 Align = Target->getPointerAlign(LangAS::Default); \
2460 break;
2461#include "clang/Basic/SPIRVTypes.def"
2462 }
2463 break;
2464 case Type::ObjCObjectPointer:
2465 Width = Target->getPointerWidth(LangAS::Default);
2466 Align = Target->getPointerAlign(LangAS::Default);
2467 break;
2468 case Type::BlockPointer:
2469 AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
2470 Width = Target->getPointerWidth(AS);
2471 Align = Target->getPointerAlign(AS);
2472 break;
2473 case Type::LValueReference:
2474 case Type::RValueReference:
2475 // alignof and sizeof should never enter this code path here, so we go
2476 // the pointer route.
2477 AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
2478 Width = Target->getPointerWidth(AS);
2479 Align = Target->getPointerAlign(AS);
2480 break;
2481 case Type::Pointer:
2482 AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
2483 Width = Target->getPointerWidth(AS);
2484 Align = Target->getPointerAlign(AS);
2485 break;
2486 case Type::MemberPointer: {
2487 const auto *MPT = cast<MemberPointerType>(T);
2488 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
2489 Width = MPI.Width;
2490 Align = MPI.Align;
2491 break;
2492 }
2493 case Type::Complex: {
2494 // Complex types have the same alignment as their elements, but twice the
2495 // size.
2496 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
2497 Width = EltInfo.Width * 2;
2498 Align = EltInfo.Align;
2499 break;
2500 }
2501 case Type::ObjCObject:
2502 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
2503 case Type::Adjusted:
2504 case Type::Decayed:
2505 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
2506 case Type::ObjCInterface: {
2507 const auto *ObjCI = cast<ObjCInterfaceType>(T);
2508 if (ObjCI->getDecl()->isInvalidDecl()) {
2509 Width = 8;
2510 Align = 8;
2511 break;
2512 }
2513 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2514 Width = toBits(Layout.getSize());
2515 Align = toBits(Layout.getAlignment());
2516 break;
2517 }
2518 case Type::BitInt: {
2519 const auto *EIT = cast<BitIntType>(T);
2520 Align = Target->getBitIntAlign(EIT->getNumBits());
2521 Width = Target->getBitIntWidth(EIT->getNumBits());
2522 break;
2523 }
2524 case Type::Record:
2525 case Type::Enum: {
2526 const auto *TT = cast<TagType>(T);
2527 const TagDecl *TD = TT->getDecl()->getDefinitionOrSelf();
2528
2529 if (TD->isInvalidDecl()) {
2530 Width = 8;
2531 Align = 8;
2532 break;
2533 }
2534
2535 if (isa<EnumType>(TT)) {
2536 const EnumDecl *ED = cast<EnumDecl>(TD);
2537 TypeInfo Info =
2539 if (unsigned AttrAlign = ED->getMaxAlignment()) {
2540 Info.Align = AttrAlign;
2542 }
2543 return Info;
2544 }
2545
2546 const auto *RD = cast<RecordDecl>(TD);
2547 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2548 Width = toBits(Layout.getSize());
2549 Align = toBits(Layout.getAlignment());
2550 AlignRequirement = RD->hasAttr<AlignedAttr>()
2552 : AlignRequirementKind::None;
2553 break;
2554 }
2555
2556 case Type::SubstTemplateTypeParm:
2558 getReplacementType().getTypePtr());
2559
2560 case Type::Auto:
2561 case Type::DeducedTemplateSpecialization: {
2562 const auto *A = cast<DeducedType>(T);
2563 assert(!A->getDeducedType().isNull() &&
2564 "cannot request the size of an undeduced or dependent auto type");
2565 return getTypeInfo(A->getDeducedType().getTypePtr());
2566 }
2567
2568 case Type::Paren:
2569 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
2570
2571 case Type::MacroQualified:
2572 return getTypeInfo(
2574
2575 case Type::ObjCTypeParam:
2576 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
2577
2578 case Type::Using:
2579 return getTypeInfo(cast<UsingType>(T)->desugar().getTypePtr());
2580
2581 case Type::Typedef: {
2582 const auto *TT = cast<TypedefType>(T);
2583 TypeInfo Info = getTypeInfo(TT->desugar().getTypePtr());
2584 // If the typedef has an aligned attribute on it, it overrides any computed
2585 // alignment we have. This violates the GCC documentation (which says that
2586 // attribute(aligned) can only round up) but matches its implementation.
2587 if (unsigned AttrAlign = TT->getDecl()->getMaxAlignment()) {
2588 Align = AttrAlign;
2589 AlignRequirement = AlignRequirementKind::RequiredByTypedef;
2590 } else {
2591 Align = Info.Align;
2592 AlignRequirement = Info.AlignRequirement;
2593 }
2594 Width = Info.Width;
2595 break;
2596 }
2597
2598 case Type::Attributed:
2599 return getTypeInfo(
2600 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
2601
2602 case Type::CountAttributed:
2603 return getTypeInfo(cast<CountAttributedType>(T)->desugar().getTypePtr());
2604
2605 case Type::LateParsedAttr:
2606 return getTypeInfo(cast<LateParsedAttrType>(T)->desugar().getTypePtr());
2607
2608 case Type::BTFTagAttributed:
2609 return getTypeInfo(
2610 cast<BTFTagAttributedType>(T)->getWrappedType().getTypePtr());
2611
2612 case Type::OverflowBehavior:
2613 return getTypeInfo(
2615
2616 case Type::HLSLAttributedResource:
2617 return getTypeInfo(
2618 cast<HLSLAttributedResourceType>(T)->getWrappedType().getTypePtr());
2619
2620 case Type::HLSLInlineSpirv: {
2621 const auto *ST = cast<HLSLInlineSpirvType>(T);
2622 // Size is specified in bytes, convert to bits
2623 Width = ST->getSize() * 8;
2624 Align = ST->getAlignment();
2625 if (Width == 0 && Align == 0) {
2626 // We are defaulting to laying out opaque SPIR-V types as 32-bit ints.
2627 Width = 32;
2628 Align = 32;
2629 }
2630 break;
2631 }
2632
2633 case Type::Atomic: {
2634 // Start with the base type information.
2635 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
2636 Width = Info.Width;
2637 Align = Info.Align;
2638
2639 if (!Width) {
2640 // An otherwise zero-sized type should still generate an
2641 // atomic operation.
2642 Width = Target->getCharWidth();
2643 assert(Align);
2644 } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2645 // If the size of the type doesn't exceed the platform's max
2646 // atomic promotion width, make the size and alignment more
2647 // favorable to atomic operations:
2648
2649 // Round the size up to a power of 2.
2650 Width = llvm::bit_ceil(Width);
2651
2652 // Raise the alignment to the size. If that would not raise it, keep the
2653 // value type's alignment and alignment requirement; it can exceed the
2654 // width only through __attribute__((aligned)) on a typedef or enum.
2655 if (Align < Width)
2656 Align = static_cast<unsigned>(Width);
2657 else
2658 AlignRequirement = Info.AlignRequirement;
2659 }
2660 }
2661 break;
2662
2663 case Type::PredefinedSugar:
2664 return getTypeInfo(cast<PredefinedSugarType>(T)->desugar().getTypePtr());
2665
2666 case Type::Pipe:
2667 Width = Target->getPointerWidth(LangAS::opencl_global);
2668 Align = Target->getPointerAlign(LangAS::opencl_global);
2669 break;
2670 }
2671
2672 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
2673 return TypeInfo(Width, Align, AlignRequirement);
2674}
2675
2677 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
2678 if (I != MemoizedUnadjustedAlign.end())
2679 return I->second;
2680
2681 unsigned UnadjustedAlign;
2682 if (const auto *RT = T->getAsCanonical<RecordType>()) {
2683 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
2684 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2685 } else if (const auto *ObjCI = T->getAsCanonical<ObjCInterfaceType>()) {
2686 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2687 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2688 } else {
2689 UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType());
2690 }
2691
2692 MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2693 return UnadjustedAlign;
2694}
2695
2697 unsigned SimdAlign = llvm::OpenMPIRBuilder::getOpenMPDefaultSimdAlign(
2698 getTargetInfo().getTriple(), Target->getTargetOpts().FeatureMap);
2699 return SimdAlign;
2700}
2701
2702/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2704 return CharUnits::fromQuantity(BitSize / getCharWidth());
2705}
2706
2707/// toBits - Convert a size in characters to a size in characters.
2708int64_t ASTContext::toBits(CharUnits CharSize) const {
2709 return CharSize.getQuantity() * getCharWidth();
2710}
2711
2712/// getTypeSizeInChars - Return the size of the specified type, in characters.
2713/// This method does not work on incomplete types.
2720
2721/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
2722/// characters. This method does not work on incomplete types.
2729
2730/// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2731/// type, in characters, before alignment adjustments. This method does
2732/// not work on incomplete types.
2739
2740/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2741/// type for the current target in bits. This can be different than the ABI
2742/// alignment in cases where it is beneficial for performance or backwards
2743/// compatibility preserving to overalign a data type. (Note: despite the name,
2744/// the preferred alignment is ABI-impacting, and not an optimization.)
2746 TypeInfo TI = getTypeInfo(T);
2747 unsigned ABIAlign = TI.Align;
2748
2749 T = T->getBaseElementTypeUnsafe();
2750
2751 // The preferred alignment of member pointers is that of a pointer.
2752 if (T->isMemberPointerType())
2753 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2754
2755 if (!Target->allowsLargerPreferedTypeAlignment())
2756 return ABIAlign;
2757
2758 if (const auto *RD = T->getAsRecordDecl()) {
2759 // When used as part of a typedef, or together with a 'packed' attribute,
2760 // the 'aligned' attribute can be used to decrease alignment. Note that the
2761 // 'packed' case is already taken into consideration when computing the
2762 // alignment, we only need to handle the typedef case here.
2764 RD->isInvalidDecl())
2765 return ABIAlign;
2766
2767 unsigned PreferredAlign = static_cast<unsigned>(
2768 toBits(getASTRecordLayout(RD).PreferredAlignment));
2769 assert(PreferredAlign >= ABIAlign &&
2770 "PreferredAlign should be at least as large as ABIAlign.");
2771 return PreferredAlign;
2772 }
2773
2774 // Double (and, for targets supporting AIX `power` alignment, long double) and
2775 // long long should be naturally aligned (despite requiring less alignment) if
2776 // possible.
2777 if (const auto *CT = T->getAs<ComplexType>())
2778 T = CT->getElementType().getTypePtr();
2779 if (const auto *ED = T->getAsEnumDecl())
2780 T = ED->getIntegerType().getTypePtr();
2781 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
2782 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2783 T->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2784 (T->isSpecificBuiltinType(BuiltinType::LongDouble) &&
2785 Target->defaultsToAIXPowerAlignment()))
2786 // Don't increase the alignment if an alignment attribute was specified on a
2787 // typedef declaration.
2788 if (!TI.isAlignRequired())
2789 return std::max(ABIAlign, (unsigned)getTypeSize(T));
2790
2791 return ABIAlign;
2792}
2793
2794/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2795/// for __attribute__((aligned)) on this target, to be used if no alignment
2796/// value is specified.
2800
2801/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2802/// to a global variable of the specified type.
2804 uint64_t TypeSize = getTypeSize(T.getTypePtr());
2805 return std::max(getPreferredTypeAlign(T),
2806 getMinGlobalAlignOfVar(TypeSize, VD));
2807}
2808
2809/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2810/// should be given to a global variable of the specified type.
2815
2817 const VarDecl *VD) const {
2818 // Make the default handling as that of a non-weak definition in the
2819 // current translation unit.
2820 bool HasNonWeakDef = !VD || (VD->hasDefinition() && !VD->isWeak());
2821 return getTargetInfo().getMinGlobalAlign(Size, HasNonWeakDef);
2822}
2823
2825 CharUnits Offset = CharUnits::Zero();
2826 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2827 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2828 Offset += Layout->getBaseClassOffset(Base);
2829 Layout = &getASTRecordLayout(Base);
2830 }
2831 return Offset;
2832}
2833
2835 const ValueDecl *MPD = MP.getMemberPointerDecl();
2838 bool DerivedMember = MP.isMemberPointerToDerivedMember();
2840 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
2841 const CXXRecordDecl *Base = RD;
2842 const CXXRecordDecl *Derived = Path[I];
2843 if (DerivedMember)
2844 std::swap(Base, Derived);
2846 RD = Path[I];
2847 }
2848 if (DerivedMember)
2850 return ThisAdjustment;
2851}
2852
2853/// DeepCollectObjCIvars -
2854/// This routine first collects all declared, but not synthesized, ivars in
2855/// super class and then collects all ivars, including those synthesized for
2856/// current class. This routine is used for implementation of current class
2857/// when all ivars, declared and synthesized are known.
2859 bool leafClass,
2861 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2862 DeepCollectObjCIvars(SuperClass, false, Ivars);
2863 if (!leafClass) {
2864 llvm::append_range(Ivars, OI->ivars());
2865 } else {
2866 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
2867 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
2868 Iv= Iv->getNextIvar())
2869 Ivars.push_back(Iv);
2870 }
2871}
2872
2873/// CollectInheritedProtocols - Collect all protocols in current class and
2874/// those inherited by it.
2877 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2878 // We can use protocol_iterator here instead of
2879 // all_referenced_protocol_iterator since we are walking all categories.
2880 for (auto *Proto : OI->all_referenced_protocols()) {
2881 CollectInheritedProtocols(Proto, Protocols);
2882 }
2883
2884 // Categories of this Interface.
2885 for (const auto *Cat : OI->visible_categories())
2886 CollectInheritedProtocols(Cat, Protocols);
2887
2888 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2889 while (SD) {
2890 CollectInheritedProtocols(SD, Protocols);
2891 SD = SD->getSuperClass();
2892 }
2893 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
2894 for (auto *Proto : OC->protocols()) {
2895 CollectInheritedProtocols(Proto, Protocols);
2896 }
2897 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
2898 // Insert the protocol.
2899 if (!Protocols.insert(
2900 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2901 return;
2902
2903 for (auto *Proto : OP->protocols())
2904 CollectInheritedProtocols(Proto, Protocols);
2905 }
2906}
2907
2909 const RecordDecl *RD,
2910 bool CheckIfTriviallyCopyable) {
2911 assert(RD->isUnion() && "Must be union type");
2912 CharUnits UnionSize =
2913 Context.getTypeSizeInChars(Context.getCanonicalTagType(RD));
2914
2915 for (const auto *Field : RD->fields()) {
2916 if (!Context.hasUniqueObjectRepresentations(Field->getType(),
2917 CheckIfTriviallyCopyable))
2918 return false;
2919 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2920 if (FieldSize != UnionSize)
2921 return false;
2922 }
2923 return !RD->field_empty();
2924}
2925
2927 const ASTContext &Context,
2928 const clang::ASTRecordLayout & /*Layout*/) {
2929 return Context.getFieldOffset(Field);
2930}
2931
2933 const ASTContext &Context,
2934 const clang::ASTRecordLayout &Layout) {
2935 return Context.toBits(Layout.getBaseClassOffset(RD));
2936}
2937
2938static std::optional<int64_t>
2940 const RecordDecl *RD,
2941 bool CheckIfTriviallyCopyable);
2942
2943static std::optional<int64_t>
2944getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context,
2945 bool CheckIfTriviallyCopyable) {
2946 if (const auto *RD = Field->getType()->getAsRecordDecl();
2947 RD && !RD->isUnion())
2948 return structHasUniqueObjectRepresentations(Context, RD,
2949 CheckIfTriviallyCopyable);
2950
2951 // A _BitInt type may not be unique if it has padding bits
2952 // but if it is a bitfield the padding bits are not used.
2953 bool IsBitIntType = Field->getType()->isBitIntType();
2954 if (!Field->getType()->isReferenceType() && !IsBitIntType &&
2955 !Context.hasUniqueObjectRepresentations(Field->getType(),
2956 CheckIfTriviallyCopyable))
2957 return std::nullopt;
2958
2959 int64_t FieldSizeInBits =
2960 Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2961 if (Field->isBitField()) {
2962 // If we have explicit padding bits, they don't contribute bits
2963 // to the actual object representation, so return 0.
2964 if (Field->isUnnamedBitField())
2965 return 0;
2966
2967 int64_t BitfieldSize = Field->getBitWidthValue();
2968 if (IsBitIntType) {
2969 if ((unsigned)BitfieldSize >
2970 cast<BitIntType>(Field->getType())->getNumBits())
2971 return std::nullopt;
2972 } else if (BitfieldSize > FieldSizeInBits) {
2973 return std::nullopt;
2974 }
2975 FieldSizeInBits = BitfieldSize;
2976 } else if (IsBitIntType && !Context.hasUniqueObjectRepresentations(
2977 Field->getType(), CheckIfTriviallyCopyable)) {
2978 return std::nullopt;
2979 }
2980 return FieldSizeInBits;
2981}
2982
2983static std::optional<int64_t>
2985 bool CheckIfTriviallyCopyable) {
2986 return structHasUniqueObjectRepresentations(Context, RD,
2987 CheckIfTriviallyCopyable);
2988}
2989
2990template <typename RangeT>
2992 const RangeT &Subobjects, int64_t CurOffsetInBits,
2993 const ASTContext &Context, const clang::ASTRecordLayout &Layout,
2994 bool CheckIfTriviallyCopyable) {
2995 for (const auto *Subobject : Subobjects) {
2996 std::optional<int64_t> SizeInBits =
2997 getSubobjectSizeInBits(Subobject, Context, CheckIfTriviallyCopyable);
2998 if (!SizeInBits)
2999 return std::nullopt;
3000 if (*SizeInBits != 0) {
3001 int64_t Offset = getSubobjectOffset(Subobject, Context, Layout);
3002 if (Offset != CurOffsetInBits)
3003 return std::nullopt;
3004 CurOffsetInBits += *SizeInBits;
3005 }
3006 }
3007 return CurOffsetInBits;
3008}
3009
3010static std::optional<int64_t>
3012 const RecordDecl *RD,
3013 bool CheckIfTriviallyCopyable) {
3014 assert(!RD->isUnion() && "Must be struct/class type");
3015 const auto &Layout = Context.getASTRecordLayout(RD);
3016
3017 int64_t CurOffsetInBits = 0;
3018 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
3019 if (ClassDecl->isDynamicClass())
3020 return std::nullopt;
3021
3023 for (const auto &Base : ClassDecl->bases()) {
3024 // Empty types can be inherited from, and non-empty types can potentially
3025 // have tail padding, so just make sure there isn't an error.
3026 Bases.emplace_back(Base.getType()->getAsCXXRecordDecl());
3027 }
3028
3029 llvm::sort(Bases, [&](const CXXRecordDecl *L, const CXXRecordDecl *R) {
3030 return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R);
3031 });
3032
3033 std::optional<int64_t> OffsetAfterBases =
3035 Bases, CurOffsetInBits, Context, Layout, CheckIfTriviallyCopyable);
3036 if (!OffsetAfterBases)
3037 return std::nullopt;
3038 CurOffsetInBits = *OffsetAfterBases;
3039 }
3040
3041 std::optional<int64_t> OffsetAfterFields =
3043 RD->fields(), CurOffsetInBits, Context, Layout,
3044 CheckIfTriviallyCopyable);
3045 if (!OffsetAfterFields)
3046 return std::nullopt;
3047 CurOffsetInBits = *OffsetAfterFields;
3048
3049 return CurOffsetInBits;
3050}
3051
3053 QualType Ty, bool CheckIfTriviallyCopyable) const {
3054 // C++17 [meta.unary.prop]:
3055 // The predicate condition for a template specialization
3056 // has_unique_object_representations<T> shall be satisfied if and only if:
3057 // (9.1) - T is trivially copyable, and
3058 // (9.2) - any two objects of type T with the same value have the same
3059 // object representation, where:
3060 // - two objects of array or non-union class type are considered to have
3061 // the same value if their respective sequences of direct subobjects
3062 // have the same values, and
3063 // - two objects of union type are considered to have the same value if
3064 // they have the same active member and the corresponding members have
3065 // the same value.
3066 // The set of scalar types for which this condition holds is
3067 // implementation-defined. [ Note: If a type has padding bits, the condition
3068 // does not hold; otherwise, the condition holds true for unsigned integral
3069 // types. -- end note ]
3070 assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
3071
3072 // Arrays are unique only if their element type is unique.
3073 if (Ty->isArrayType())
3075 CheckIfTriviallyCopyable);
3076
3077 assert((Ty->isVoidType() || !Ty->isIncompleteType()) &&
3078 "hasUniqueObjectRepresentations should not be called with an "
3079 "incomplete type");
3080
3081 // _Atomic(T) shares T's object representation unless its size was rounded
3082 // up to a power of two, in which case the extra bytes are padding. Atomic
3083 // types are never trivially copyable, so (9.1) is judged on the value type.
3084 if (const auto *AT = Ty->getAs<AtomicType>())
3085 return getTypeSize(AT) == getTypeSize(AT->getValueType()) &&
3086 hasUniqueObjectRepresentations(AT->getValueType(),
3087 CheckIfTriviallyCopyable);
3088
3089 // (9.1) - T is trivially copyable...
3090 if (CheckIfTriviallyCopyable && !Ty.isTriviallyCopyableType(*this))
3091 return false;
3092
3093 // All integrals and enums are unique.
3094 if (Ty->isIntegralOrEnumerationType()) {
3095 // Address discriminated integer types are not unique.
3097 return false;
3098 // Except _BitInt types that have padding bits.
3099 if (const auto *BIT = Ty->getAs<BitIntType>())
3100 return getTypeSize(BIT) == BIT->getNumBits();
3101
3102 return true;
3103 }
3104
3105 // All other pointers are unique.
3106 if (Ty->isPointerType())
3108
3109 if (const auto *MPT = Ty->getAs<MemberPointerType>())
3110 return !ABI->getMemberPointerInfo(MPT).HasPadding;
3111
3112 if (const auto *Record = Ty->getAsRecordDecl()) {
3113 if (Record->isInvalidDecl())
3114 return false;
3115
3116 if (Record->isUnion())
3118 CheckIfTriviallyCopyable);
3119
3120 std::optional<int64_t> StructSize = structHasUniqueObjectRepresentations(
3121 *this, Record, CheckIfTriviallyCopyable);
3122
3123 return StructSize && *StructSize == static_cast<int64_t>(getTypeSize(Ty));
3124 }
3125
3126 // FIXME: More cases to handle here (list by rsmith):
3127 // vectors (careful about, eg, vector of 3 foo)
3128 // _Complex int and friends
3129 // Obj-C block pointers
3130 // Obj-C object pointers
3131 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
3132 // clk_event_t, queue_t, reserve_id_t)
3133 // There're also Obj-C class types and the Obj-C selector type, but I think it
3134 // makes sense for those to return false here.
3135
3136 return false;
3137}
3138
3140 unsigned count = 0;
3141 // Count ivars declared in class extension.
3142 for (const auto *Ext : OI->known_extensions())
3143 count += Ext->ivar_size();
3144
3145 // Count ivar defined in this class's implementation. This
3146 // includes synthesized ivars.
3147 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
3148 count += ImplDecl->ivar_size();
3149
3150 return count;
3151}
3152
3154 if (!E)
3155 return false;
3156
3157 // nullptr_t is always treated as null.
3158 if (E->getType()->isNullPtrType()) return true;
3159
3160 if (E->getType()->isAnyPointerType() &&
3163 return true;
3164
3165 // Unfortunately, __null has type 'int'.
3166 if (isa<GNUNullExpr>(E)) return true;
3167
3168 return false;
3169}
3170
3171/// Get the implementation of ObjCInterfaceDecl, or nullptr if none
3172/// exists.
3174 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
3175 I = ObjCImpls.find(D);
3176 if (I != ObjCImpls.end())
3177 return cast<ObjCImplementationDecl>(I->second);
3178 return nullptr;
3179}
3180
3181/// Get the implementation of ObjCCategoryDecl, or nullptr if none
3182/// exists.
3184 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
3185 I = ObjCImpls.find(D);
3186 if (I != ObjCImpls.end())
3187 return cast<ObjCCategoryImplDecl>(I->second);
3188 return nullptr;
3189}
3190
3191/// Set the implementation of ObjCInterfaceDecl.
3193 ObjCImplementationDecl *ImplD) {
3194 assert(IFaceD && ImplD && "Passed null params");
3195 ObjCImpls[IFaceD] = ImplD;
3196}
3197
3198/// Set the implementation of ObjCCategoryDecl.
3200 ObjCCategoryImplDecl *ImplD) {
3201 assert(CatD && ImplD && "Passed null params");
3202 ObjCImpls[CatD] = ImplD;
3203}
3204
3205const ObjCMethodDecl *
3207 return ObjCMethodRedecls.lookup(MD);
3208}
3209
3211 const ObjCMethodDecl *Redecl) {
3212 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
3213 ObjCMethodRedecls[MD] = Redecl;
3214}
3215
3217 const NamedDecl *ND) const {
3218 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
3219 return ID;
3220 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
3221 return CD->getClassInterface();
3222 if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
3223 return IMD->getClassInterface();
3224
3225 return nullptr;
3226}
3227
3228/// Get the copy initialization expression of VarDecl, or nullptr if
3229/// none exists.
3231 assert(VD && "Passed null params");
3232 assert(VD->hasAttr<BlocksAttr>() &&
3233 "getBlockVarCopyInits - not __block var");
3234 auto I = BlockVarCopyInits.find(VD);
3235 if (I != BlockVarCopyInits.end())
3236 return I->second;
3237 return {nullptr, false};
3238}
3239
3240/// Set the copy initialization expression of a block var decl.
3242 bool CanThrow) {
3243 assert(VD && CopyExpr && "Passed null params");
3244 assert(VD->hasAttr<BlocksAttr>() &&
3245 "setBlockVarCopyInits - not __block var");
3246 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
3247}
3248
3250 unsigned DataSize) const {
3251 if (!DataSize)
3253 else
3254 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
3255 "incorrect data size provided to CreateTypeSourceInfo!");
3256
3257 auto *TInfo =
3258 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
3259 new (TInfo) TypeSourceInfo(T, DataSize);
3260 return TInfo;
3261}
3262
3264 SourceLocation L) const {
3266 TSI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
3267 return TSI;
3268}
3269
3270const ASTRecordLayout &
3272 return getObjCLayout(D);
3273}
3274
3277 bool &AnyNonCanonArgs) {
3278 SmallVector<TemplateArgument, 16> CanonArgs(Args);
3279 AnyNonCanonArgs |= C.canonicalizeTemplateArguments(CanonArgs);
3280 return CanonArgs;
3281}
3282
3285 bool AnyNonCanonArgs = false;
3286 for (auto &Arg : Args) {
3287 TemplateArgument OrigArg = Arg;
3289 AnyNonCanonArgs |= !Arg.structurallyEquals(OrigArg);
3290 }
3291 return AnyNonCanonArgs;
3292}
3293
3294//===----------------------------------------------------------------------===//
3295// Type creation/memoization methods
3296//===----------------------------------------------------------------------===//
3297
3299ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
3300 unsigned fastQuals = quals.getFastQualifiers();
3301 quals.removeFastQualifiers();
3302
3303 // Check if we've already instantiated this type.
3304 llvm::FoldingSetNodeID ID;
3305 ExtQuals::Profile(ID, baseType, quals);
3306 llvm::FoldingSetInsertToken Token;
3307 if (ExtQuals *eq = ExtQualNodes.lookup(ID, Token)) {
3308 assert(eq->getQualifiers() == quals);
3309 return QualType(eq, fastQuals);
3310 }
3311
3312 // If the base type is not canonical, make the appropriate canonical type.
3313 QualType canon;
3314 if (!baseType->isCanonicalUnqualified()) {
3315 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
3316 canonSplit.Quals.addConsistentQualifiers(quals);
3317 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
3318
3319 // Re-find the insert position.
3320 (void)ExtQualNodes.lookup(ID, Token);
3321 }
3322
3323 auto *eq = new (*this, alignof(ExtQuals)) ExtQuals(baseType, canon, quals);
3324 ExtQualNodes.insert(eq, Token);
3325 return QualType(eq, fastQuals);
3326}
3327
3329 LangAS AddressSpace) const {
3330 QualType CanT = getCanonicalType(T);
3331 if (CanT.getAddressSpace() == AddressSpace)
3332 return T;
3333
3334 // If we are composing extended qualifiers together, merge together
3335 // into one ExtQuals node.
3336 QualifierCollector Quals;
3337 const Type *TypeNode = Quals.strip(T);
3338
3339 // If this type already has an address space specified, it cannot get
3340 // another one.
3341 assert(!Quals.hasAddressSpace() &&
3342 "Type cannot be in multiple addr spaces!");
3343 Quals.addAddressSpace(AddressSpace);
3344
3345 return getExtQualType(TypeNode, Quals);
3346}
3347
3349 // If the type is not qualified with an address space, just return it
3350 // immediately.
3351 if (!T.hasAddressSpace())
3352 return T;
3353
3354 QualifierCollector Quals;
3355 const Type *TypeNode;
3356 // For arrays, strip the qualifier off the element type, then reconstruct the
3357 // array type
3358 if (T.getTypePtr()->isArrayType()) {
3359 T = getUnqualifiedArrayType(T, Quals);
3360 TypeNode = T.getTypePtr();
3361 } else {
3362 // If we are composing extended qualifiers together, merge together
3363 // into one ExtQuals node.
3364 while (T.hasAddressSpace()) {
3365 TypeNode = Quals.strip(T);
3366
3367 // If the type no longer has an address space after stripping qualifiers,
3368 // jump out.
3369 if (!QualType(TypeNode, 0).hasAddressSpace())
3370 break;
3371
3372 // There might be sugar in the way. Strip it and try again.
3373 T = T.getSingleStepDesugaredType(*this);
3374 }
3375 }
3376
3377 Quals.removeAddressSpace();
3378
3379 // Removal of the address space can mean there are no longer any
3380 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
3381 // or required.
3382 if (Quals.hasNonFastQualifiers())
3383 return getExtQualType(TypeNode, Quals);
3384 else
3385 return QualType(TypeNode, Quals.getFastQualifiers());
3386}
3387
3388uint16_t
3390 bool IsVTTEntry) {
3391 assert(RD->isPolymorphic() &&
3392 "Attempted to get vtable pointer discriminator on a monomorphic type");
3393
3394 std::unique_ptr<MangleContext> MC(createMangleContext());
3395 SmallString<256> Str;
3396 llvm::raw_svector_ostream Out(Str);
3397 MC->mangleCXXVTable(RD, Out);
3398 if (IsVTTEntry)
3400 return llvm::getPointerAuthStableSipHash(Str);
3401}
3402
3403/// Encode a function type for use in the discriminator of a function pointer
3404/// type. We can't use the itanium scheme for this since C has quite permissive
3405/// rules for type compatibility that we need to be compatible with.
3406///
3407/// Formally, this function associates every function pointer type T with an
3408/// encoded string E(T). Let the equivalence relation T1 ~ T2 be defined as
3409/// E(T1) == E(T2). E(T) is part of the ABI of values of type T. C type
3410/// compatibility requires equivalent treatment under the ABI, so
3411/// CCompatible(T1, T2) must imply E(T1) == E(T2), that is, CCompatible must be
3412/// a subset of ~. Crucially, however, it must be a proper subset because
3413/// CCompatible is not an equivalence relation: for example, int[] is compatible
3414/// with both int[1] and int[2], but the latter are not compatible with each
3415/// other. Therefore this encoding function must be careful to only distinguish
3416/// types if there is no third type with which they are both required to be
3417/// compatible.
3419 raw_ostream &OS, QualType QT) {
3420 // FIXME: Consider address space qualifiers.
3421 const Type *T = QT.getCanonicalType().getTypePtr();
3422
3423 // FIXME: Consider using the C++ type mangling when we encounter a construct
3424 // that is incompatible with C.
3425
3426 switch (T->getTypeClass()) {
3427 case Type::Atomic:
3429 Ctx, OS, cast<AtomicType>(T)->getValueType());
3430
3431 case Type::LValueReference:
3432 OS << "R";
3435 return;
3436 case Type::RValueReference:
3437 OS << "O";
3440 return;
3441
3442 case Type::Pointer:
3443 // C11 6.7.6.1p2:
3444 // For two pointer types to be compatible, both shall be identically
3445 // qualified and both shall be pointers to compatible types.
3446 // FIXME: we should also consider pointee types.
3447 OS << "P";
3448 return;
3449
3450 case Type::ObjCObjectPointer:
3451 case Type::BlockPointer:
3452 OS << "P";
3453 return;
3454
3455 case Type::Complex:
3456 OS << "C";
3458 Ctx, OS, cast<ComplexType>(T)->getElementType());
3459
3460 case Type::VariableArray:
3461 case Type::ConstantArray:
3462 case Type::IncompleteArray:
3463 case Type::ArrayParameter:
3464 // C11 6.7.6.2p6:
3465 // For two array types to be compatible, both shall have compatible
3466 // element types, and if both size specifiers are present, and are integer
3467 // constant expressions, then both size specifiers shall have the same
3468 // constant value [...]
3469 //
3470 // So since ElemType[N] has to be compatible ElemType[], we can't encode the
3471 // width of the array.
3472 OS << "A";
3474 Ctx, OS, cast<ArrayType>(T)->getElementType());
3475
3476 case Type::ObjCInterface:
3477 case Type::ObjCObject:
3478 OS << "<objc_object>";
3479 return;
3480
3481 case Type::Enum: {
3482 // C11 6.7.2.2p4:
3483 // Each enumerated type shall be compatible with char, a signed integer
3484 // type, or an unsigned integer type.
3485 //
3486 // So we have to treat enum types as integers.
3487 QualType UnderlyingType = T->castAsEnumDecl()->getIntegerType();
3489 Ctx, OS, UnderlyingType.isNull() ? Ctx.IntTy : UnderlyingType);
3490 }
3491
3492 case Type::FunctionNoProto:
3493 case Type::FunctionProto: {
3494 // C11 6.7.6.3p15:
3495 // For two function types to be compatible, both shall specify compatible
3496 // return types. Moreover, the parameter type lists, if both are present,
3497 // shall agree in the number of parameters and in the use of the ellipsis
3498 // terminator; corresponding parameters shall have compatible types.
3499 //
3500 // That paragraph goes on to describe how unprototyped functions are to be
3501 // handled, which we ignore here. Unprototyped function pointers are hashed
3502 // as though they were prototyped nullary functions since thats probably
3503 // what the user meant. This behavior is non-conforming.
3504 // FIXME: If we add a "custom discriminator" function type attribute we
3505 // should encode functions as their discriminators.
3506 OS << "F";
3507 const auto *FuncType = cast<FunctionType>(T);
3508 encodeTypeForFunctionPointerAuth(Ctx, OS, FuncType->getReturnType());
3509 if (const auto *FPT = dyn_cast<FunctionProtoType>(FuncType)) {
3510 for (QualType Param : FPT->param_types()) {
3511 Param = Ctx.getSignatureParameterType(Param);
3512 encodeTypeForFunctionPointerAuth(Ctx, OS, Param);
3513 }
3514 if (FPT->isVariadic())
3515 OS << "z";
3516 }
3517 OS << "E";
3518 return;
3519 }
3520
3521 case Type::MemberPointer: {
3522 OS << "M";
3523 const auto *MPT = T->castAs<MemberPointerType>();
3525 Ctx, OS, QualType(MPT->getQualifier().getAsType(), 0));
3526 encodeTypeForFunctionPointerAuth(Ctx, OS, MPT->getPointeeType());
3527 return;
3528 }
3529 case Type::ExtVector:
3530 case Type::Vector:
3531 OS << "Dv" << Ctx.getTypeSizeInChars(T).getQuantity();
3532 break;
3533
3534 // Don't bother discriminating based on these types.
3535 case Type::Pipe:
3536 case Type::BitInt:
3537 case Type::ConstantMatrix:
3538 OS << "?";
3539 return;
3540
3541 case Type::Builtin: {
3542 const auto *BTy = T->castAs<BuiltinType>();
3543 switch (BTy->getKind()) {
3544#define SIGNED_TYPE(Id, SingletonId) \
3545 case BuiltinType::Id: \
3546 OS << "i"; \
3547 return;
3548#define UNSIGNED_TYPE(Id, SingletonId) \
3549 case BuiltinType::Id: \
3550 OS << "i"; \
3551 return;
3552#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
3553#define BUILTIN_TYPE(Id, SingletonId)
3554#include "clang/AST/BuiltinTypes.def"
3555 llvm_unreachable("placeholder types should not appear here.");
3556
3557 case BuiltinType::Half:
3558 OS << "Dh";
3559 return;
3560 case BuiltinType::Float:
3561 OS << "f";
3562 return;
3563 case BuiltinType::Double:
3564 OS << "d";
3565 return;
3566 case BuiltinType::LongDouble:
3567 OS << "e";
3568 return;
3569 case BuiltinType::Float16:
3570 OS << "DF16_";
3571 return;
3572 case BuiltinType::Float128:
3573 OS << "g";
3574 return;
3575
3576 case BuiltinType::Void:
3577 OS << "v";
3578 return;
3579
3580 case BuiltinType::ObjCId:
3581 case BuiltinType::ObjCClass:
3582 case BuiltinType::ObjCSel:
3583 case BuiltinType::NullPtr:
3584 OS << "P";
3585 return;
3586
3587 // Don't bother discriminating based on OpenCL types.
3588 case BuiltinType::OCLSampler:
3589 case BuiltinType::OCLEvent:
3590 case BuiltinType::OCLClkEvent:
3591 case BuiltinType::OCLQueue:
3592 case BuiltinType::OCLReserveID:
3593 case BuiltinType::BFloat16:
3594 case BuiltinType::VectorQuad:
3595 case BuiltinType::VectorPair:
3596 case BuiltinType::DMR1024:
3597 case BuiltinType::DMR2048:
3598 case BuiltinType::MetaInfo:
3599 OS << "?";
3600 return;
3601
3602 // Don't bother discriminating based on these seldom-used types.
3603 case BuiltinType::Ibm128:
3604 return;
3605#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
3606 case BuiltinType::Id: \
3607 return;
3608#include "clang/Basic/OpenCLImageTypes.def"
3609#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
3610 case BuiltinType::Id: \
3611 return;
3612#include "clang/Basic/OpenCLExtensionTypes.def"
3613#define SVE_TYPE(Name, Id, SingletonId) \
3614 case BuiltinType::Id: \
3615 return;
3616#include "clang/Basic/AArch64ACLETypes.def"
3617#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
3618 case BuiltinType::Id: \
3619 return;
3620#include "clang/Basic/HLSLIntangibleTypes.def"
3621#define HLSL_PACKED_TYPE(Name, Id, SingletonId) \
3622 case BuiltinType::Id: \
3623 return;
3624#include "clang/Basic/HLSLPackedTypes.def"
3625 case BuiltinType::Dependent:
3626 llvm_unreachable("should never get here");
3627#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
3628#include "clang/Basic/AMDGPUTypes.def"
3629 case BuiltinType::WasmExternRef:
3630#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
3631#include "clang/Basic/RISCVVTypes.def"
3632#define SPIRV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
3633#include "clang/Basic/SPIRVTypes.def"
3634 llvm_unreachable("not yet implemented");
3635 }
3636 llvm_unreachable("should never get here");
3637 }
3638 case Type::Record: {
3639 const RecordDecl *RD = T->castAsCanonical<RecordType>()->getDecl();
3640 const IdentifierInfo *II = RD->getIdentifier();
3641
3642 // In C++, an immediate typedef of an anonymous struct or union
3643 // is considered to name it for ODR purposes, but C's specification
3644 // of type compatibility does not have a similar rule. Using the typedef
3645 // name in function type discriminators anyway, as we do here,
3646 // therefore technically violates the C standard: two function pointer
3647 // types defined in terms of two typedef'd anonymous structs with
3648 // different names are formally still compatible, but we are assigning
3649 // them different discriminators and therefore incompatible ABIs.
3650 //
3651 // This is a relatively minor violation that significantly improves
3652 // discrimination in some cases and has not caused problems in
3653 // practice. Regardless, it is now part of the ABI in places where
3654 // function type discrimination is used, and it can no longer be
3655 // changed except on new platforms.
3656
3657 if (!II)
3658 if (const TypedefNameDecl *Typedef = RD->getTypedefNameForAnonDecl())
3659 II = Typedef->getDeclName().getAsIdentifierInfo();
3660
3661 if (!II) {
3662 OS << "<anonymous_record>";
3663 return;
3664 }
3665 OS << II->getLength() << II->getName();
3666 return;
3667 }
3668 case Type::HLSLAttributedResource:
3669 case Type::HLSLInlineSpirv:
3670 llvm_unreachable("should never get here");
3671 break;
3672 case Type::OverflowBehavior:
3673 llvm_unreachable("should never get here");
3674 break;
3675 case Type::DeducedTemplateSpecialization:
3676 case Type::Auto:
3677#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3678#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3679#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3680#define ABSTRACT_TYPE(Class, Base)
3681#define TYPE(Class, Base)
3682#include "clang/AST/TypeNodes.inc"
3683 llvm_unreachable("unexpected non-canonical or dependent type!");
3684 return;
3685 }
3686}
3687
3689 assert(!T->isDependentType() &&
3690 "cannot compute type discriminator of a dependent type");
3691 SmallString<256> Str;
3692 llvm::raw_svector_ostream Out(Str);
3693
3694 if (T->isFunctionPointerType() || T->isFunctionReferenceType())
3695 T = T->getPointeeType();
3696
3697 if (T->isFunctionType()) {
3699 } else {
3700 T = T.getUnqualifiedType();
3701 // Calls to member function pointers don't need to worry about
3702 // language interop or the laxness of the C type compatibility rules.
3703 // We just mangle the member pointer type directly, which is
3704 // implicitly much stricter about type matching. However, we do
3705 // strip any top-level exception specification before this mangling.
3706 // C++23 requires calls to work when the function type is convertible
3707 // to the pointer type by a function pointer conversion, which can
3708 // change the exception specification. This does not technically
3709 // require the exception specification to not affect representation,
3710 // because the function pointer conversion is still always a direct
3711 // value conversion and therefore an opportunity to resign the
3712 // pointer. (This is in contrast to e.g. qualification conversions,
3713 // which can be applied in nested pointer positions, effectively
3714 // requiring qualified and unqualified representations to match.)
3715 // However, it is pragmatic to ignore exception specifications
3716 // because it allows a certain amount of `noexcept` mismatching
3717 // to not become a visible ODR problem. This also leaves some
3718 // room for the committee to add laxness to function pointer
3719 // conversions in future standards.
3720 if (auto *MPT = T->getAs<MemberPointerType>())
3721 if (MPT->isMemberFunctionPointer()) {
3722 QualType PointeeType = MPT->getPointeeType();
3723 if (PointeeType->castAs<FunctionProtoType>()->getExceptionSpecType() !=
3724 EST_None) {
3726 T = getMemberPointerType(FT, MPT->getQualifier(),
3727 MPT->getMostRecentCXXRecordDecl());
3728 }
3729 }
3730 std::unique_ptr<MangleContext> MC(createMangleContext());
3731 MC->mangleCanonicalTypeName(T, Out);
3732 }
3733
3734 return llvm::getPointerAuthStableSipHash(Str);
3735}
3736
3738 Qualifiers::GC GCAttr) const {
3739 QualType CanT = getCanonicalType(T);
3740 if (CanT.getObjCGCAttr() == GCAttr)
3741 return T;
3742
3743 if (const auto *ptr = T->getAs<PointerType>()) {
3744 QualType Pointee = ptr->getPointeeType();
3745 if (Pointee->isAnyPointerType()) {
3746 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
3747 return getPointerType(ResultType);
3748 }
3749 }
3750
3751 // If we are composing extended qualifiers together, merge together
3752 // into one ExtQuals node.
3753 QualifierCollector Quals;
3754 const Type *TypeNode = Quals.strip(T);
3755
3756 // If this type already has an ObjCGC specified, it cannot get
3757 // another one.
3758 assert(!Quals.hasObjCGCAttr() &&
3759 "Type cannot have multiple ObjCGCs!");
3760 Quals.addObjCGCAttr(GCAttr);
3761
3762 return getExtQualType(TypeNode, Quals);
3763}
3764
3766 if (const PointerType *Ptr = T->getAs<PointerType>()) {
3767 QualType Pointee = Ptr->getPointeeType();
3768 if (isPtrSizeAddressSpace(Pointee.getAddressSpace())) {
3769 return getPointerType(removeAddrSpaceQualType(Pointee));
3770 }
3771 }
3772 return T;
3773}
3774
3776 QualType WrappedTy, Expr *CountExpr, bool CountInBytes, bool OrNull,
3777 ArrayRef<TypeCoupledDeclRefInfo> DependentDecls) const {
3778 assert(WrappedTy->isPointerType() || WrappedTy->isArrayType());
3779 assert(CountExpr && "use getIncompleteCountAttributedType for a null count");
3780
3781 // Complete (non-late-parsed) path: the count expression is known up front.
3782 // This deliberately preserves the pre-existing uniquing behavior -- the
3783 // FoldingSet lookup/insert below is unchanged by late-parse support. Only
3784 // getIncompleteCountAttributedType (count filled in later) opts out of
3785 // uniquing.
3786 llvm::FoldingSetNodeID ID;
3787 CountAttributedType::Profile(ID, WrappedTy, CountExpr, CountInBytes, OrNull);
3788
3789 llvm::FoldingSetInsertToken Token;
3790 CountAttributedType *CATy = CountAttributedTypes.lookup(ID, Token);
3791 if (CATy)
3792 return QualType(CATy, 0);
3793
3794 QualType CanonTy = getCanonicalType(WrappedTy);
3795 CATy = CountAttributedType::Create(*this, WrappedTy, CanonTy, CountExpr,
3796 CountInBytes, OrNull, DependentDecls);
3797 Types.push_back(CATy);
3798 CountAttributedTypes.insert(CATy, Token);
3799
3800 return QualType(CATy, 0);
3801}
3802
3804 QualType WrappedTy, bool CountInBytes, bool OrNull) const {
3805 assert(WrappedTy->isPointerType() || WrappedTy->isArrayType());
3806
3807 // Deliberately opts out of the uniquing that `getCountAttributedType` does:
3808 // `CountAttributedType::Profile` keys on the `CountExpr` pointer, which is
3809 // null here, so every incomplete node would profile identically as
3810 // `(WrappedTy, flags, nullptr)` and two fields with different counts would
3811 // collide. The node stays un-uniqued even after completion; see
3812 // `completeCountAttributedType`.
3813 //
3814 // Also deliberately not in `Types` yet. An incomplete node can be abandoned
3815 // without ever being completed (a nested counted_by, or an argument that
3816 // fails to parse), and a null-count node must not be reachable by anything
3817 // that scans `Types`. `completeCountAttributedType` registers it once the
3818 // count is in place.
3819 return CountAttributedType::Create(
3820 *this, WrappedTy, getCanonicalType(WrappedTy),
3821 /*CountExpr=*/nullptr, CountInBytes, OrNull,
3822 /*CoupledDecls=*/{});
3823}
3824
3826 CountAttributedType *CATy, Expr *CountExpr,
3827 ArrayRef<TypeCoupledDeclRefInfo> DependentDecls) const {
3828 CATy->complete(*this, CountExpr, DependentDecls);
3829 // Safe for `Types` scanners now that the count is in place; see
3830 // `getIncompleteCountAttributedType` for why it was held back.
3831 //
3832 // It stays out of the `CountAttributedTypes` FoldingSet permanently, unlike
3833 // an eagerly built node: this pointer is already embedded in the enclosing
3834 // types and handed out, so an equal node that happens to exist cannot be
3835 // merged into. The only cost is that a completed node is never
3836 // pointer-shared with an equal eager one, which does not affect semantic
3837 // type equality -- `hasSameType` compares canonical types, and this sugar's
3838 // canonical type is the wrapped type's.
3839 Types.push_back(CATy);
3840}
3841
3843 QualType WrappedTy, LateParsedTypeAttribute *LateParsedAttr) const {
3844 QualType CanonTy = getCanonicalType(WrappedTy);
3845
3846 auto *LPATy = new (*this, alignof(LateParsedAttrType))
3847 LateParsedAttrType(WrappedTy, CanonTy, LateParsedAttr);
3848
3849 Types.push_back(LPATy);
3850 return QualType(LPATy, 0);
3851}
3852
3855 llvm::function_ref<QualType(QualType)> Adjust) const {
3856 switch (Orig->getTypeClass()) {
3857 case Type::Attributed: {
3858 const auto *AT = cast<AttributedType>(Orig);
3859 return getAttributedType(AT->getAttrKind(),
3860 adjustType(AT->getModifiedType(), Adjust),
3861 adjustType(AT->getEquivalentType(), Adjust),
3862 AT->getAttr());
3863 }
3864
3865 case Type::BTFTagAttributed: {
3866 const auto *BTFT = dyn_cast<BTFTagAttributedType>(Orig);
3867 return getBTFTagAttributedType(BTFT->getAttr(),
3868 adjustType(BTFT->getWrappedType(), Adjust));
3869 }
3870
3871 case Type::OverflowBehavior: {
3872 const auto *OB = dyn_cast<OverflowBehaviorType>(Orig);
3873 return getOverflowBehaviorType(OB->getBehaviorKind(),
3874 adjustType(OB->getUnderlyingType(), Adjust));
3875 }
3876
3877 case Type::Paren:
3878 return getParenType(
3879 adjustType(cast<ParenType>(Orig)->getInnerType(), Adjust));
3880
3881 case Type::Adjusted: {
3882 const auto *AT = cast<AdjustedType>(Orig);
3883 return getAdjustedType(AT->getOriginalType(),
3884 adjustType(AT->getAdjustedType(), Adjust));
3885 }
3886
3887 case Type::MacroQualified: {
3888 const auto *MQT = cast<MacroQualifiedType>(Orig);
3889 return getMacroQualifiedType(adjustType(MQT->getUnderlyingType(), Adjust),
3890 MQT->getMacroIdentifier());
3891 }
3892
3893 default:
3894 return Adjust(Orig);
3895 }
3896}
3897
3899 FunctionType::ExtInfo Info) {
3900 if (T->getExtInfo() == Info)
3901 return T;
3902
3904 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
3905 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
3906 } else {
3907 const auto *FPT = cast<FunctionProtoType>(T);
3908 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
3909 EPI.ExtInfo = Info;
3910 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
3911 }
3912
3913 return cast<FunctionType>(Result.getTypePtr());
3914}
3915
3917 QualType ResultType) {
3918 return adjustType(FunctionType, [&](QualType Orig) {
3919 if (const auto *FNPT = Orig->getAs<FunctionNoProtoType>())
3920 return getFunctionNoProtoType(ResultType, FNPT->getExtInfo());
3921
3922 const auto *FPT = Orig->castAs<FunctionProtoType>();
3923 return getFunctionType(ResultType, FPT->getParamTypes(),
3924 FPT->getExtProtoInfo());
3925 });
3926}
3927
3929 QualType ResultType) {
3930 FD = FD->getMostRecentDecl();
3931 while (true) {
3932 FD->setType(adjustFunctionResultType(FD->getType(), ResultType));
3933 if (FunctionDecl *Next = FD->getPreviousDecl())
3934 FD = Next;
3935 else
3936 break;
3937 }
3939 L->DeducedReturnType(FD, ResultType);
3940}
3941
3942/// Get a function type and produce the equivalent function type with the
3943/// specified exception specification. Type sugar that can be present on a
3944/// declaration of a function with an exception specification is permitted
3945/// and preserved. Other type sugar (for instance, typedefs) is not.
3947 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const {
3948 return adjustType(Orig, [&](QualType Ty) {
3949 const auto *Proto = Ty->castAs<FunctionProtoType>();
3950 return getFunctionType(Proto->getReturnType(), Proto->getParamTypes(),
3951 Proto->getExtProtoInfo().withExceptionSpec(ESI));
3952 });
3953}
3954
3962
3964 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3965 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3966 SmallVector<QualType, 16> Args(Proto->param_types().size());
3967 for (unsigned i = 0, n = Args.size(); i != n; ++i)
3968 Args[i] = removePtrSizeAddrSpace(Proto->param_types()[i]);
3969 return getFunctionType(RetTy, Args, Proto->getExtProtoInfo());
3970 }
3971
3972 if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) {
3973 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3974 return getFunctionNoProtoType(RetTy, Proto->getExtInfo());
3975 }
3976
3977 return T;
3978}
3979
3985
3987 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3988 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3989 EPI.ExtParameterInfos = nullptr;
3990 return getFunctionType(Proto->getReturnType(), Proto->param_types(), EPI);
3991 }
3992 return T;
3993}
3994
4000
4003 bool AsWritten) {
4004 // Update the type.
4005 QualType Updated =
4007 FD->setType(Updated);
4008
4009 if (!AsWritten)
4010 return;
4011
4012 // Update the type in the type source information too.
4013 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
4014 // If the type and the type-as-written differ, we may need to update
4015 // the type-as-written too.
4016 if (TSInfo->getType() != FD->getType())
4017 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
4018
4019 // FIXME: When we get proper type location information for exceptions,
4020 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
4021 // up the TypeSourceInfo;
4022 assert(TypeLoc::getFullDataSizeForType(Updated) ==
4023 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
4024 "TypeLoc size mismatch from updating exception specification");
4025 TSInfo->overrideType(Updated);
4026 }
4027}
4028
4029/// getComplexType - Return the uniqued reference to the type for a complex
4030/// number with the specified element type.
4032 // Unique pointers, to guarantee there is only one pointer of a particular
4033 // structure.
4034 llvm::FoldingSetInsertToken Token;
4035 if (ComplexType *CT = ComplexTypes.lookup(T, Token))
4036 return QualType(CT, 0);
4037
4038 // If the pointee type isn't canonical, this won't be a canonical type either,
4039 // so fill in the canonical type field.
4040 QualType Canonical;
4041 if (!T.isCanonical()) {
4042 Canonical = getComplexType(getCanonicalType(T));
4043
4044 assert(!ComplexTypes.lookup(T, Token) && "Shouldn't be in the map!");
4045 }
4046 auto *New = new (*this, alignof(ComplexType)) ComplexType(T, Canonical);
4047 Types.push_back(New);
4048 ComplexTypes.insert(New, Token);
4049 return QualType(New, 0);
4050}
4051
4052/// getPointerType - Return the uniqued reference to the type for a pointer to
4053/// the specified type.
4055 // Unique pointers, to guarantee there is only one pointer of a particular
4056 // structure.
4057 llvm::FoldingSetInsertToken Token;
4058 if (PointerType *PT = PointerTypes.lookup(T, Token))
4059 return QualType(PT, 0);
4060
4061 // If the pointee type isn't canonical, this won't be a canonical type either,
4062 // so fill in the canonical type field.
4063 QualType Canonical;
4064 if (!T.isCanonical()) {
4065 Canonical = getPointerType(getCanonicalType(T));
4066
4067 assert(!PointerTypes.lookup(T, Token) && "Shouldn't be in the map!");
4068 }
4069 auto *New = new (*this, alignof(PointerType)) PointerType(T, Canonical);
4070 Types.push_back(New);
4071 PointerTypes.insert(New, Token);
4072 return QualType(New, 0);
4073}
4074
4076 llvm::FoldingSetInsertToken Token;
4077 AdjustedType *AT = AdjustedTypes.lookup({Orig, New}, Token);
4078 if (AT)
4079 return QualType(AT, 0);
4080
4081 QualType Canonical = getCanonicalType(New);
4082
4083 AT = new (*this, alignof(AdjustedType))
4084 AdjustedType(Type::Adjusted, Orig, New, Canonical);
4085 Types.push_back(AT);
4086 AdjustedTypes.insert(AT, Token);
4087 return QualType(AT, 0);
4088}
4089
4091 llvm::FoldingSetInsertToken Token;
4092 AdjustedType *AT = AdjustedTypes.lookup({Orig, Decayed}, Token);
4093 if (AT)
4094 return QualType(AT, 0);
4095
4096 QualType Canonical = getCanonicalType(Decayed);
4097
4098 AT = new (*this, alignof(DecayedType)) DecayedType(Orig, Decayed, Canonical);
4099 Types.push_back(AT);
4100 AdjustedTypes.insert(AT, Token);
4101 return QualType(AT, 0);
4102}
4103
4105 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
4106
4107 QualType Decayed;
4108
4109 // C99 6.7.5.3p7:
4110 // A declaration of a parameter as "array of type" shall be
4111 // adjusted to "qualified pointer to type", where the type
4112 // qualifiers (if any) are those specified within the [ and ] of
4113 // the array type derivation.
4114 if (T->isArrayType())
4115 Decayed = getArrayDecayedType(T);
4116
4117 // C99 6.7.5.3p8:
4118 // A declaration of a parameter as "function returning type"
4119 // shall be adjusted to "pointer to function returning type", as
4120 // in 6.3.2.1.
4121 if (T->isFunctionType())
4122 Decayed = getPointerType(T);
4123
4124 return getDecayedType(T, Decayed);
4125}
4126
4128 if (Ty->isArrayParameterType())
4129 return Ty;
4130 assert(Ty->isConstantArrayType() && "Ty must be an array type.");
4131 QualType DTy = Ty.getDesugaredType(*this);
4132 const auto *ATy = cast<ConstantArrayType>(DTy);
4133 llvm::FoldingSetNodeID ID;
4134 ATy->Profile(ID, *this, ATy->getElementType(), ATy->getZExtSize(),
4135 ATy->getSizeExpr(), ATy->getSizeModifier(),
4136 ATy->getIndexTypeQualifiers().getAsOpaqueValue());
4137 llvm::FoldingSetInsertToken Token;
4138 ArrayParameterType *AT = ArrayParameterTypes.lookup(ID, Token);
4139 if (AT)
4140 return QualType(AT, 0);
4141
4142 QualType Canonical;
4143 if (!DTy.isCanonical()) {
4144 Canonical = getArrayParameterType(getCanonicalType(Ty));
4145
4146 // Get the new insert position for the node we care about.
4147 AT = ArrayParameterTypes.lookup(ID, Token);
4148 assert(!AT && "Shouldn't be in the map!");
4149 }
4150
4151 AT = new (*this, alignof(ArrayParameterType))
4152 ArrayParameterType(ATy, Canonical);
4153 Types.push_back(AT);
4154 ArrayParameterTypes.insert(AT, Token);
4155 return QualType(AT, 0);
4156}
4157
4158/// getBlockPointerType - Return the uniqued reference to the type for
4159/// a pointer to the specified block.
4161 assert(T->isFunctionType() && "block of function types only");
4162 // Unique pointers, to guarantee there is only one block of a particular
4163 // structure.
4164 llvm::FoldingSetInsertToken Token;
4165 if (BlockPointerType *PT = BlockPointerTypes.lookup(T, Token))
4166 return QualType(PT, 0);
4167
4168 // If the block pointee type isn't canonical, this won't be a canonical
4169 // type either so fill in the canonical type field.
4170 QualType Canonical;
4171 if (!T.isCanonical()) {
4173
4174 assert(!BlockPointerTypes.lookup(T, Token) && "Shouldn't be in the map!");
4175 }
4176 auto *New =
4177 new (*this, alignof(BlockPointerType)) BlockPointerType(T, Canonical);
4178 Types.push_back(New);
4179 BlockPointerTypes.insert(New, Token);
4180 return QualType(New, 0);
4181}
4182
4183/// getLValueReferenceType - Return the uniqued reference to the type for an
4184/// lvalue reference to the specified type.
4186ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
4187 assert((!T->isPlaceholderType() ||
4188 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
4189 "Unresolved placeholder type");
4190
4191 // Unique pointers, to guarantee there is only one pointer of a particular
4192 // structure.
4193 llvm::FoldingSetInsertToken Token;
4194 if (LValueReferenceType *RT =
4195 LValueReferenceTypes.lookup({T, SpelledAsLValue}, Token))
4196 return QualType(RT, 0);
4197
4198 const auto *InnerRef = T->getAs<ReferenceType>();
4199
4200 // If the referencee type isn't canonical, this won't be a canonical type
4201 // either, so fill in the canonical type field.
4202 QualType Canonical;
4203 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
4204 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
4205 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
4206
4207 assert(!LValueReferenceTypes.lookup({T, SpelledAsLValue}, Token) &&
4208 "Shouldn't be in the map!");
4209 }
4210
4211 auto *New = new (*this, alignof(LValueReferenceType))
4212 LValueReferenceType(T, Canonical, SpelledAsLValue);
4213 Types.push_back(New);
4214 LValueReferenceTypes.insert(New, Token);
4215
4216 return QualType(New, 0);
4217}
4218
4219/// getRValueReferenceType - Return the uniqued reference to the type for an
4220/// rvalue reference to the specified type.
4222 assert((!T->isPlaceholderType() ||
4223 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
4224 "Unresolved placeholder type");
4225
4226 // Unique pointers, to guarantee there is only one pointer of a particular
4227 // structure.
4228 llvm::FoldingSetInsertToken Token;
4229 if (RValueReferenceType *RT = RValueReferenceTypes.lookup({T, false}, Token))
4230 return QualType(RT, 0);
4231
4232 const auto *InnerRef = T->getAs<ReferenceType>();
4233
4234 // If the referencee type isn't canonical, this won't be a canonical type
4235 // either, so fill in the canonical type field.
4236 QualType Canonical;
4237 if (InnerRef || !T.isCanonical()) {
4238 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
4239 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
4240
4241 assert(!RValueReferenceTypes.lookup({T, false}, Token) &&
4242 "Shouldn't be in the map!");
4243 }
4244
4245 auto *New = new (*this, alignof(RValueReferenceType))
4246 RValueReferenceType(T, Canonical);
4247 Types.push_back(New);
4248 RValueReferenceTypes.insert(New, Token);
4249 return QualType(New, 0);
4250}
4251
4253 NestedNameSpecifier Qualifier,
4254 const CXXRecordDecl *Cls) const {
4255 if (!Qualifier) {
4256 assert(Cls && "At least one of Qualifier or Cls must be provided");
4257 Qualifier = NestedNameSpecifier(getCanonicalTagType(Cls).getTypePtr());
4258 } else if (!Cls) {
4259 Cls = Qualifier.getAsRecordDecl();
4260 }
4261 // Unique pointers, to guarantee there is only one pointer of a particular
4262 // structure.
4263 llvm::FoldingSetNodeID ID;
4264 MemberPointerType::Profile(ID, T, Qualifier, Cls);
4265
4266 llvm::FoldingSetInsertToken Token;
4267 if (MemberPointerType *PT = MemberPointerTypes.lookup(ID, Token))
4268 return QualType(PT, 0);
4269
4270 NestedNameSpecifier CanonicalQualifier = [&] {
4271 if (!Cls)
4272 return Qualifier.getCanonical();
4273 NestedNameSpecifier R(getCanonicalTagType(Cls).getTypePtr());
4274 assert(R.isCanonical());
4275 return R;
4276 }();
4277 // If the pointee or class type isn't canonical, this won't be a canonical
4278 // type either, so fill in the canonical type field.
4279 QualType Canonical;
4280 if (!T.isCanonical() || Qualifier != CanonicalQualifier) {
4281 Canonical =
4282 getMemberPointerType(getCanonicalType(T), CanonicalQualifier, Cls);
4283 assert(!cast<MemberPointerType>(Canonical)->isSugared());
4284 // Get the new insert position for the node we care about.
4285 [[maybe_unused]] MemberPointerType *NewIP =
4286 MemberPointerTypes.lookup(ID, Token);
4287 assert(!NewIP && "Shouldn't be in the map!");
4288 }
4289 auto *New = new (*this, alignof(MemberPointerType))
4290 MemberPointerType(T, Qualifier, Canonical);
4291 Types.push_back(New);
4292 MemberPointerTypes.insert(New, Token);
4293 return QualType(New, 0);
4294}
4295
4296/// getConstantArrayType - Return the unique reference to the type for an
4297/// array of the specified element type.
4299 const llvm::APInt &ArySizeIn,
4300 const Expr *SizeExpr,
4302 unsigned IndexTypeQuals) const {
4303 assert((EltTy->isDependentType() ||
4304 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
4305 "Constant array of VLAs is illegal!");
4306
4307 // We only need the size as part of the type if it's instantiation-dependent.
4308 if (SizeExpr && !SizeExpr->isInstantiationDependent())
4309 SizeExpr = nullptr;
4310
4311 // Convert the array size into a canonical width matching the pointer size for
4312 // the target.
4313 llvm::APInt ArySize(ArySizeIn);
4314 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
4315
4316 llvm::FoldingSetNodeID ID;
4317 ConstantArrayType::Profile(ID, *this, EltTy, ArySize.getZExtValue(), SizeExpr,
4318 ASM, IndexTypeQuals);
4319
4320 llvm::FoldingSetInsertToken Token;
4321 if (ConstantArrayType *ATP = ConstantArrayTypes.lookup(ID, Token))
4322 return QualType(ATP, 0);
4323
4324 // If the element type isn't canonical or has qualifiers, or the array bound
4325 // is instantiation-dependent, this won't be a canonical type either, so fill
4326 // in the canonical type field.
4327 QualType Canon;
4328 // FIXME: Check below should look for qualifiers behind sugar.
4329 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) {
4330 SplitQualType canonSplit = getCanonicalType(EltTy).split();
4331 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr,
4332 ASM, IndexTypeQuals);
4333 Canon = getQualifiedType(Canon, canonSplit.Quals);
4334
4335 // Get the new insert position for the node we care about.
4336 ConstantArrayType *NewIP = ConstantArrayTypes.lookup(ID, Token);
4337 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4338 }
4339
4340 auto *New = ConstantArrayType::Create(*this, EltTy, Canon, ArySize, SizeExpr,
4341 ASM, IndexTypeQuals);
4342 ConstantArrayTypes.insert(New, Token);
4343 Types.push_back(New);
4344 return QualType(New, 0);
4345}
4346
4347/// getVariableArrayDecayedType - Turns the given type, which may be
4348/// variably-modified, into the corresponding type with all the known
4349/// sizes replaced with [*].
4351 // Vastly most common case.
4352 if (!type->isVariablyModifiedType()) return type;
4353
4354 QualType result;
4355
4356 SplitQualType split = type.getSplitDesugaredType();
4357 const Type *ty = split.Ty;
4358 switch (ty->getTypeClass()) {
4359#define TYPE(Class, Base)
4360#define ABSTRACT_TYPE(Class, Base)
4361#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4362#include "clang/AST/TypeNodes.inc"
4363 llvm_unreachable("didn't desugar past all non-canonical types?");
4364
4365 // These types should never be variably-modified.
4366 case Type::Builtin:
4367 case Type::Complex:
4368 case Type::Vector:
4369 case Type::DependentVector:
4370 case Type::ExtVector:
4371 case Type::DependentSizedExtVector:
4372 case Type::ConstantMatrix:
4373 case Type::DependentSizedMatrix:
4374 case Type::DependentAddressSpace:
4375 case Type::ObjCObject:
4376 case Type::ObjCInterface:
4377 case Type::ObjCObjectPointer:
4378 case Type::Record:
4379 case Type::Enum:
4380 case Type::UnresolvedUsing:
4381 case Type::TypeOfExpr:
4382 case Type::TypeOf:
4383 case Type::Decltype:
4384 case Type::UnaryTransform:
4385 case Type::DependentName:
4386 case Type::InjectedClassName:
4387 case Type::TemplateSpecialization:
4388 case Type::TemplateTypeParm:
4389 case Type::SubstTemplateTypeParmPack:
4390 case Type::SubstBuiltinTemplatePack:
4391 case Type::Auto:
4392 case Type::DeducedTemplateSpecialization:
4393 case Type::PackExpansion:
4394 case Type::PackIndexing:
4395 case Type::BitInt:
4396 case Type::DependentBitInt:
4397 case Type::ArrayParameter:
4398 case Type::HLSLAttributedResource:
4399 case Type::HLSLInlineSpirv:
4400 case Type::OverflowBehavior:
4401 llvm_unreachable("type should never be variably-modified");
4402
4403 // These types can be variably-modified but should never need to
4404 // further decay.
4405 case Type::FunctionNoProto:
4406 case Type::FunctionProto:
4407 case Type::BlockPointer:
4408 case Type::MemberPointer:
4409 case Type::Pipe:
4410 return type;
4411
4412 // These types can be variably-modified. All these modifications
4413 // preserve structure except as noted by comments.
4414 // TODO: if we ever care about optimizing VLAs, there are no-op
4415 // optimizations available here.
4416 case Type::Pointer:
4419 break;
4420
4421 case Type::LValueReference: {
4422 const auto *lv = cast<LValueReferenceType>(ty);
4423 result = getLValueReferenceType(
4424 getVariableArrayDecayedType(lv->getPointeeType()),
4425 lv->isSpelledAsLValue());
4426 break;
4427 }
4428
4429 case Type::RValueReference: {
4430 const auto *lv = cast<RValueReferenceType>(ty);
4431 result = getRValueReferenceType(
4432 getVariableArrayDecayedType(lv->getPointeeType()));
4433 break;
4434 }
4435
4436 case Type::Atomic: {
4437 const auto *at = cast<AtomicType>(ty);
4438 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
4439 break;
4440 }
4441
4442 case Type::ConstantArray: {
4443 const auto *cat = cast<ConstantArrayType>(ty);
4444 result = getConstantArrayType(
4445 getVariableArrayDecayedType(cat->getElementType()),
4446 cat->getSize(),
4447 cat->getSizeExpr(),
4448 cat->getSizeModifier(),
4449 cat->getIndexTypeCVRQualifiers());
4450 break;
4451 }
4452
4453 case Type::DependentSizedArray: {
4454 const auto *dat = cast<DependentSizedArrayType>(ty);
4456 getVariableArrayDecayedType(dat->getElementType()), dat->getSizeExpr(),
4457 dat->getSizeModifier(), dat->getIndexTypeCVRQualifiers());
4458 break;
4459 }
4460
4461 // Turn incomplete types into [*] types.
4462 case Type::IncompleteArray: {
4463 const auto *iat = cast<IncompleteArrayType>(ty);
4464 result =
4466 /*size*/ nullptr, ArraySizeModifier::Normal,
4467 iat->getIndexTypeCVRQualifiers());
4468 break;
4469 }
4470
4471 // Turn VLA types into [*] types.
4472 case Type::VariableArray: {
4473 const auto *vat = cast<VariableArrayType>(ty);
4474 result =
4476 /*size*/ nullptr, ArraySizeModifier::Star,
4477 vat->getIndexTypeCVRQualifiers());
4478 break;
4479 }
4480 }
4481
4482 // Apply the top-level qualifiers from the original.
4483 return getQualifiedType(result, split.Quals);
4484}
4485
4486/// getVariableArrayType - Returns a non-unique reference to the type for a
4487/// variable array of the specified element type.
4490 unsigned IndexTypeQuals) const {
4491 // Since we don't unique expressions, it isn't possible to unique VLA's
4492 // that have an expression provided for their size.
4493 QualType Canon;
4494
4495 // Be sure to pull qualifiers off the element type.
4496 // FIXME: Check below should look for qualifiers behind sugar.
4497 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
4498 SplitQualType canonSplit = getCanonicalType(EltTy).split();
4499 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
4500 IndexTypeQuals);
4501 Canon = getQualifiedType(Canon, canonSplit.Quals);
4502 }
4503
4504 auto *New = new (*this, alignof(VariableArrayType))
4505 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals);
4506
4507 VariableArrayTypes.push_back(New);
4508 Types.push_back(New);
4509 return QualType(New, 0);
4510}
4511
4512/// getDependentSizedArrayType - Returns a non-unique reference to
4513/// the type for a dependently-sized array of the specified element
4514/// type.
4518 unsigned elementTypeQuals) const {
4519 assert((!numElements || numElements->isTypeDependent() ||
4520 numElements->isValueDependent()) &&
4521 "Size must be type- or value-dependent!");
4522
4523 SplitQualType canonElementType = getCanonicalType(elementType).split();
4524
4525 llvm::FoldingSetInsertToken Token;
4526 llvm::FoldingSetNodeID ID;
4528 ID, *this, numElements ? QualType(canonElementType.Ty, 0) : elementType,
4529 ASM, elementTypeQuals, numElements);
4530
4531 // Look for an existing type with these properties.
4532 DependentSizedArrayType *canonTy = DependentSizedArrayTypes.lookup(ID, Token);
4533
4534 // Dependently-sized array types that do not have a specified number
4535 // of elements will have their sizes deduced from a dependent
4536 // initializer.
4537 if (!numElements) {
4538 if (canonTy)
4539 return QualType(canonTy, 0);
4540
4541 auto *newType = new (*this, alignof(DependentSizedArrayType))
4542 DependentSizedArrayType(elementType, QualType(), numElements, ASM,
4543 elementTypeQuals);
4544 DependentSizedArrayTypes.insert(newType, Token);
4545 Types.push_back(newType);
4546 return QualType(newType, 0);
4547 }
4548
4549 // If we don't have one, build one.
4550 if (!canonTy) {
4551 canonTy = new (*this, alignof(DependentSizedArrayType))
4552 DependentSizedArrayType(QualType(canonElementType.Ty, 0), QualType(),
4553 numElements, ASM, elementTypeQuals);
4554 DependentSizedArrayTypes.insert(canonTy, Token);
4555 Types.push_back(canonTy);
4556 }
4557
4558 // Apply qualifiers from the element type to the array.
4559 QualType canon = getQualifiedType(QualType(canonTy,0),
4560 canonElementType.Quals);
4561
4562 // If we didn't need extra canonicalization for the element type or the size
4563 // expression, then just use that as our result.
4564 if (QualType(canonElementType.Ty, 0) == elementType &&
4565 canonTy->getSizeExpr() == numElements)
4566 return canon;
4567
4568 // Otherwise, we need to build a type which follows the spelling
4569 // of the element type.
4570 auto *sugaredType = new (*this, alignof(DependentSizedArrayType))
4571 DependentSizedArrayType(elementType, canon, numElements, ASM,
4572 elementTypeQuals);
4573 Types.push_back(sugaredType);
4574 return QualType(sugaredType, 0);
4575}
4576
4579 unsigned elementTypeQuals) const {
4580 llvm::FoldingSetNodeID ID;
4581 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
4582
4583 llvm::FoldingSetInsertToken Token;
4584 if (IncompleteArrayType *iat = IncompleteArrayTypes.lookup(ID, Token))
4585 return QualType(iat, 0);
4586
4587 // If the element type isn't canonical, this won't be a canonical type
4588 // either, so fill in the canonical type field. We also have to pull
4589 // qualifiers off the element type.
4590 QualType canon;
4591
4592 // FIXME: Check below should look for qualifiers behind sugar.
4593 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
4594 SplitQualType canonSplit = getCanonicalType(elementType).split();
4595 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
4596 ASM, elementTypeQuals);
4597 canon = getQualifiedType(canon, canonSplit.Quals);
4598
4599 // Get the new insert position for the node we care about.
4600 IncompleteArrayType *existing = IncompleteArrayTypes.lookup(ID, Token);
4601 assert(!existing && "Shouldn't be in the map!"); (void) existing;
4602 }
4603
4604 auto *newType = new (*this, alignof(IncompleteArrayType))
4605 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
4606
4607 IncompleteArrayTypes.insert(newType, Token);
4608 Types.push_back(newType);
4609 return QualType(newType, 0);
4610}
4611
4614#define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS) \
4615 {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount::getScalable(ELTS), \
4616 NUMVECTORS};
4617
4618#define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS) \
4619 {ELTTY, llvm::ElementCount::getScalable(ELTS), NUMVECTORS};
4620
4621 switch (Ty->getKind()) {
4622 default:
4623 llvm_unreachable("Unsupported builtin vector type");
4624
4625#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4626 ElBits, NF, IsSigned) \
4627 case BuiltinType::Id: \
4628 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4629 llvm::ElementCount::getScalable(NumEls), NF};
4630#define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4631 ElBits, NF) \
4632 case BuiltinType::Id: \
4633 return {ElBits == 16 ? HalfTy : (ElBits == 32 ? FloatTy : DoubleTy), \
4634 llvm::ElementCount::getScalable(NumEls), NF};
4635#define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4636 ElBits, NF) \
4637 case BuiltinType::Id: \
4638 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4639#define SVE_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4640 ElBits, NF) \
4641 case BuiltinType::Id: \
4642 return {MFloat8Ty, llvm::ElementCount::getScalable(NumEls), NF};
4643#define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4644 case BuiltinType::Id: \
4645 return {BoolTy, llvm::ElementCount::getScalable(NumEls), NF};
4646#include "clang/Basic/AArch64ACLETypes.def"
4647
4648#define RVV_VECTOR_TYPE_INT(Name, Id, SingletonId, NumEls, ElBits, NF, \
4649 IsSigned) \
4650 case BuiltinType::Id: \
4651 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4652 llvm::ElementCount::getScalable(NumEls), NF};
4653#define RVV_VECTOR_TYPE_FLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4654 case BuiltinType::Id: \
4655 return {ElBits == 16 ? Float16Ty : (ElBits == 32 ? FloatTy : DoubleTy), \
4656 llvm::ElementCount::getScalable(NumEls), NF};
4657#define RVV_VECTOR_TYPE_BFLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4658 case BuiltinType::Id: \
4659 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4660#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4661 case BuiltinType::Id: \
4662 return {BoolTy, llvm::ElementCount::getScalable(NumEls), 1};
4663#include "clang/Basic/RISCVVTypes.def"
4664 }
4665}
4666
4667/// getExternrefType - Return a WebAssembly externref type, which represents an
4668/// opaque reference to a host value.
4670 if (Target->getTriple().isWasm() && Target->hasFeature("reference-types")) {
4671#define WASM_REF_TYPE(Name, MangledName, Id, SingletonId, AS) \
4672 if (BuiltinType::Id == BuiltinType::WasmExternRef) \
4673 return SingletonId;
4674#include "clang/Basic/WebAssemblyReferenceTypes.def"
4675 }
4676 llvm_unreachable(
4677 "shouldn't try to generate type externref outside WebAssembly target");
4678}
4679
4680/// getScalableVectorType - Return the unique reference to a scalable vector
4681/// type of the specified element type and size. VectorType must be a built-in
4682/// type.
4684 unsigned NumFields) const {
4685 auto K = llvm::ScalableVecTyKey{EltTy, NumElts, NumFields};
4686 if (auto It = ScalableVecTyMap.find(K); It != ScalableVecTyMap.end())
4687 return It->second;
4688
4689 if (Target->hasAArch64ACLETypes()) {
4690 uint64_t EltTySize = getTypeSize(EltTy);
4691
4692#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4693 ElBits, NF, IsSigned) \
4694 if (EltTy->hasIntegerRepresentation() && !EltTy->isBooleanType() && \
4695 EltTy->hasSignedIntegerRepresentation() == IsSigned && \
4696 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4697 return ScalableVecTyMap[K] = SingletonId; \
4698 }
4699#define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4700 ElBits, NF) \
4701 if (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4702 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4703 return ScalableVecTyMap[K] = SingletonId; \
4704 }
4705#define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4706 ElBits, NF) \
4707 if (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4708 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4709 return ScalableVecTyMap[K] = SingletonId; \
4710 }
4711#define SVE_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4712 ElBits, NF) \
4713 if (EltTy->isMFloat8Type() && EltTySize == ElBits && \
4714 NumElts == (NumEls * NF) && NumFields == 1) { \
4715 return ScalableVecTyMap[K] = SingletonId; \
4716 }
4717#define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4718 if (EltTy->isBooleanType() && NumElts == (NumEls * NF) && NumFields == 1) \
4719 return ScalableVecTyMap[K] = SingletonId;
4720#include "clang/Basic/AArch64ACLETypes.def"
4721 } else if (Target->hasRISCVVTypes()) {
4722 uint64_t EltTySize = getTypeSize(EltTy);
4723#define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned, \
4724 IsFP, IsBF) \
4725 if (!EltTy->isBooleanType() && \
4726 ((EltTy->hasIntegerRepresentation() && \
4727 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \
4728 (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4729 IsFP && !IsBF) || \
4730 (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4731 IsBF && !IsFP)) && \
4732 EltTySize == ElBits && NumElts == NumEls && NumFields == NF) \
4733 return ScalableVecTyMap[K] = SingletonId;
4734#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4735 if (EltTy->isBooleanType() && NumElts == NumEls) \
4736 return ScalableVecTyMap[K] = SingletonId;
4737#include "clang/Basic/RISCVVTypes.def"
4738 }
4739 return QualType();
4740}
4741
4742/// getVectorType - Return the unique reference to a vector type of
4743/// the specified element type and size. VectorType must be a built-in type.
4745 VectorKind VecKind) const {
4746 assert(vecType->isBuiltinType() ||
4747 (vecType->isBitIntType() &&
4748 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4749 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits())));
4750
4751 // Check if we've already instantiated a vector of this type.
4752 llvm::FoldingSetNodeID ID;
4753 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
4754
4755 llvm::FoldingSetInsertToken Token;
4756 if (VectorType *VTP = VectorTypes.lookup(ID, Token))
4757 return QualType(VTP, 0);
4758
4759 // If the element type isn't canonical, this won't be a canonical type either,
4760 // so fill in the canonical type field.
4761 QualType Canonical;
4762 if (!vecType.isCanonical()) {
4763 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
4764
4765 // Get the new insert position for the node we care about.
4766 VectorType *NewIP = VectorTypes.lookup(ID, Token);
4767 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4768 }
4769 auto *New = new (*this, alignof(VectorType))
4770 VectorType(vecType, NumElts, Canonical, VecKind);
4771 VectorTypes.insert(New, Token);
4772 Types.push_back(New);
4773 return QualType(New, 0);
4774}
4775
4777 SourceLocation AttrLoc,
4778 VectorKind VecKind) const {
4779 llvm::FoldingSetNodeID ID;
4780 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
4781 VecKind);
4782 llvm::FoldingSetInsertToken Token;
4783 DependentVectorType *Canon = DependentVectorTypes.lookup(ID, Token);
4785
4786 if (Canon) {
4787 New = new (*this, alignof(DependentVectorType)) DependentVectorType(
4788 VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
4789 } else {
4790 QualType CanonVecTy = getCanonicalType(VecType);
4791 if (CanonVecTy == VecType) {
4792 New = new (*this, alignof(DependentVectorType))
4793 DependentVectorType(VecType, QualType(), SizeExpr, AttrLoc, VecKind);
4794
4795 DependentVectorType *CanonCheck = DependentVectorTypes.lookup(ID, Token);
4796 assert(!CanonCheck &&
4797 "Dependent-sized vector_size canonical type broken");
4798 (void)CanonCheck;
4799 DependentVectorTypes.insert(New, Token);
4800 } else {
4801 QualType CanonTy = getDependentVectorType(CanonVecTy, SizeExpr,
4802 SourceLocation(), VecKind);
4803 New = new (*this, alignof(DependentVectorType))
4804 DependentVectorType(VecType, CanonTy, SizeExpr, AttrLoc, VecKind);
4805 }
4806 }
4807
4808 Types.push_back(New);
4809 return QualType(New, 0);
4810}
4811
4812/// getExtVectorType - Return the unique reference to an extended vector type of
4813/// the specified element type and size. VectorType must be a built-in type.
4815 unsigned NumElts) const {
4816 assert(vecType->isBuiltinType() || vecType->isDependentType() ||
4817 (vecType->isBitIntType() &&
4818 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4819 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits())));
4820
4821 // Check if we've already instantiated a vector of this type.
4822 llvm::FoldingSetNodeID ID;
4823 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
4825 llvm::FoldingSetInsertToken Token;
4826 if (VectorType *VTP = VectorTypes.lookup(ID, Token))
4827 return QualType(VTP, 0);
4828
4829 // If the element type isn't canonical, this won't be a canonical type either,
4830 // so fill in the canonical type field.
4831 QualType Canonical;
4832 if (!vecType.isCanonical()) {
4833 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
4834
4835 // Get the new insert position for the node we care about.
4836 VectorType *NewIP = VectorTypes.lookup(ID, Token);
4837 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4838 }
4839 auto *New = new (*this, alignof(ExtVectorType))
4840 ExtVectorType(vecType, NumElts, Canonical);
4841 VectorTypes.insert(New, Token);
4842 Types.push_back(New);
4843 return QualType(New, 0);
4844}
4845
4848 Expr *SizeExpr,
4849 SourceLocation AttrLoc) const {
4850 llvm::FoldingSetNodeID ID;
4852 SizeExpr);
4853
4854 llvm::FoldingSetInsertToken Token;
4856 DependentSizedExtVectorTypes.lookup(ID, Token);
4858 if (Canon) {
4859 // We already have a canonical version of this array type; use it as
4860 // the canonical type for a newly-built type.
4861 New = new (*this, alignof(DependentSizedExtVectorType))
4862 DependentSizedExtVectorType(vecType, QualType(Canon, 0), SizeExpr,
4863 AttrLoc);
4864 } else {
4865 QualType CanonVecTy = getCanonicalType(vecType);
4866 if (CanonVecTy == vecType) {
4867 New = new (*this, alignof(DependentSizedExtVectorType))
4868 DependentSizedExtVectorType(vecType, QualType(), SizeExpr, AttrLoc);
4869
4870 DependentSizedExtVectorType *CanonCheck =
4871 DependentSizedExtVectorTypes.lookup(ID, Token);
4872 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
4873 (void)CanonCheck;
4874 DependentSizedExtVectorTypes.insert(New, Token);
4875 } else {
4876 QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
4877 SourceLocation());
4878 New = new (*this, alignof(DependentSizedExtVectorType))
4879 DependentSizedExtVectorType(vecType, CanonExtTy, SizeExpr, AttrLoc);
4880 }
4881 }
4882
4883 Types.push_back(New);
4884 return QualType(New, 0);
4885}
4886
4888 QualType ElementTy, unsigned NumRows, unsigned NumColumns,
4889 std::optional<MatrixType::LayoutKind> Layout) const {
4890 llvm::FoldingSetNodeID ID;
4891 ConstantMatrixType::Profile(ID, ElementTy, NumRows, NumColumns, Layout,
4892 Type::ConstantMatrix);
4893
4894 assert(MatrixType::isValidElementType(ElementTy, getLangOpts()) &&
4895 "need a valid element type");
4896 assert(NumRows > 0 && NumRows <= LangOpts.MaxMatrixDimension &&
4897 NumColumns > 0 && NumColumns <= LangOpts.MaxMatrixDimension &&
4898 "need valid matrix dimensions");
4899 llvm::FoldingSetInsertToken Token;
4900 if (ConstantMatrixType *MTP = MatrixTypes.lookup(ID, Token))
4901 return QualType(MTP, 0);
4902
4903 QualType Canonical;
4904 if (Layout || !ElementTy.isCanonical()) {
4905 Canonical = getConstantMatrixType(getCanonicalType(ElementTy), NumRows,
4906 NumColumns, std::nullopt);
4907
4908 ConstantMatrixType *NewIP = MatrixTypes.lookup(ID, Token);
4909 assert(!NewIP && "Matrix type shouldn't already exist in the map");
4910 (void)NewIP;
4911 }
4912
4913 auto *New = new (*this, alignof(ConstantMatrixType))
4914 ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical, Layout);
4915 MatrixTypes.insert(New, Token);
4916 Types.push_back(New);
4917 return QualType(New, 0);
4918}
4919
4921 Expr *RowExpr,
4922 Expr *ColumnExpr,
4923 SourceLocation AttrLoc) const {
4924 QualType CanonElementTy = getCanonicalType(ElementTy);
4925 llvm::FoldingSetNodeID ID;
4926 DependentSizedMatrixType::Profile(ID, *this, CanonElementTy, RowExpr,
4927 ColumnExpr);
4928
4929 llvm::FoldingSetInsertToken Token;
4930 DependentSizedMatrixType *Canon = DependentSizedMatrixTypes.lookup(ID, Token);
4931
4932 if (!Canon) {
4933 Canon = new (*this, alignof(DependentSizedMatrixType))
4934 DependentSizedMatrixType(CanonElementTy, QualType(), RowExpr,
4935 ColumnExpr, AttrLoc);
4936#ifndef NDEBUG
4937 DependentSizedMatrixType *CanonCheck =
4938 DependentSizedMatrixTypes.lookup(ID, Token);
4939 assert(!CanonCheck && "Dependent-sized matrix canonical type broken");
4940#endif
4941 DependentSizedMatrixTypes.insert(Canon, Token);
4942 Types.push_back(Canon);
4943 }
4944
4945 // Already have a canonical version of the matrix type
4946 //
4947 // If it exactly matches the requested type, use it directly.
4948 if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr &&
4949 Canon->getRowExpr() == ColumnExpr)
4950 return QualType(Canon, 0);
4951
4952 // Use Canon as the canonical type for newly-built type.
4954 DependentSizedMatrixType(ElementTy, QualType(Canon, 0), RowExpr,
4955 ColumnExpr, AttrLoc);
4956 Types.push_back(New);
4957 return QualType(New, 0);
4958}
4959
4962 MatrixType::LayoutKind Layout) const {
4963 Qualifiers Quals = T.getQualifiers();
4964 const Type *Ty = T->getUnqualifiedDesugaredType();
4965
4966 if (const auto *MT = dyn_cast<ConstantMatrixType>(Ty))
4967 return getQualifiedType(getConstantMatrixType(MT->getElementType(),
4968 MT->getNumRows(),
4969 MT->getNumColumns(), Layout),
4970 Quals);
4971
4972 const auto *CAT = dyn_cast<ConstantArrayType>(Ty);
4973 if (!CAT)
4974 return T;
4975
4977 getMatrixTypeWithLayout(CAT->getElementType(), Layout), CAT->getSize(),
4978 CAT->getSizeExpr(), CAT->getSizeModifier(),
4979 CAT->getIndexTypeCVRQualifiers());
4980 if (isa<ArrayParameterType>(CAT))
4982
4983 return getQualifiedType(Result, Quals);
4984}
4985
4987 Expr *AddrSpaceExpr,
4988 SourceLocation AttrLoc) const {
4989 assert(AddrSpaceExpr->isInstantiationDependent());
4990
4991 QualType canonPointeeType = getCanonicalType(PointeeType);
4992
4993 llvm::FoldingSetInsertToken Token;
4994 llvm::FoldingSetNodeID ID;
4995 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
4996 AddrSpaceExpr);
4997
4998 DependentAddressSpaceType *canonTy =
4999 DependentAddressSpaceTypes.lookup(ID, Token);
5000
5001 if (!canonTy) {
5002 canonTy = new (*this, alignof(DependentAddressSpaceType))
5003 DependentAddressSpaceType(canonPointeeType, QualType(), AddrSpaceExpr,
5004 AttrLoc);
5005 DependentAddressSpaceTypes.insert(canonTy, Token);
5006 Types.push_back(canonTy);
5007 }
5008
5009 if (canonPointeeType == PointeeType &&
5010 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
5011 return QualType(canonTy, 0);
5012
5013 auto *sugaredType = new (*this, alignof(DependentAddressSpaceType))
5014 DependentAddressSpaceType(PointeeType, QualType(canonTy, 0),
5015 AddrSpaceExpr, AttrLoc);
5016 Types.push_back(sugaredType);
5017 return QualType(sugaredType, 0);
5018}
5019
5020/// Determine whether \p T is canonical as the result type of a function.
5022 return T.isCanonical() &&
5023 (T.getObjCLifetime() == Qualifiers::OCL_None ||
5024 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
5025}
5026
5027/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
5028QualType
5030 const FunctionType::ExtInfo &Info) const {
5031 // FIXME: This assertion cannot be enabled (yet) because the ObjC rewriter
5032 // functionality creates a function without a prototype regardless of
5033 // language mode (so it makes them even in C++). Once the rewriter has been
5034 // fixed, this assertion can be enabled again.
5035 //assert(!LangOpts.requiresStrictPrototypes() &&
5036 // "strict prototypes are disabled");
5037
5038 // Unique functions, to guarantee there is only one function of a particular
5039 // structure.
5040 llvm::FoldingSetNodeID ID;
5041 FunctionNoProtoType::Profile(ID, ResultTy, Info);
5042
5043 llvm::FoldingSetInsertToken Token;
5044 if (FunctionNoProtoType *FT = FunctionNoProtoTypes.lookup(ID, Token))
5045 return QualType(FT, 0);
5046
5047 QualType Canonical;
5048 if (!isCanonicalResultType(ResultTy)) {
5049 Canonical =
5051
5052 // Get the new insert position for the node we care about.
5053 FunctionNoProtoType *NewIP = FunctionNoProtoTypes.lookup(ID, Token);
5054 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
5055 }
5056
5057 auto *New = new (*this, alignof(FunctionNoProtoType))
5058 FunctionNoProtoType(ResultTy, Canonical, Info);
5059 Types.push_back(New);
5060 FunctionNoProtoTypes.insert(New, Token);
5061 return QualType(New, 0);
5062}
5063
5066 CanQualType CanResultType = getCanonicalType(ResultType);
5067
5068 // Canonical result types do not have ARC lifetime qualifiers.
5069 if (CanResultType.getQualifiers().hasObjCLifetime()) {
5070 Qualifiers Qs = CanResultType.getQualifiers();
5071 Qs.removeObjCLifetime();
5073 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
5074 }
5075
5076 return CanResultType;
5077}
5078
5080 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
5081 if (ESI.Type == EST_None)
5082 return true;
5083 if (!NoexceptInType)
5084 return false;
5085
5086 // C++17 onwards: exception specification is part of the type, as a simple
5087 // boolean "can this function type throw".
5088 if (ESI.Type == EST_BasicNoexcept)
5089 return true;
5090
5091 // A noexcept(expr) specification is (possibly) canonical if expr is
5092 // value-dependent.
5093 if (ESI.Type == EST_DependentNoexcept)
5094 return true;
5095
5096 // A dynamic exception specification is canonical if it only contains pack
5097 // expansions (so we can't tell whether it's non-throwing) and all its
5098 // contained types are canonical.
5099 if (ESI.Type == EST_Dynamic) {
5100 bool AnyPackExpansions = false;
5101 for (QualType ET : ESI.Exceptions) {
5102 if (!ET.isCanonical())
5103 return false;
5104 if (ET->getAs<PackExpansionType>())
5105 AnyPackExpansions = true;
5106 }
5107 return AnyPackExpansions;
5108 }
5109
5110 return false;
5111}
5112
5113QualType ASTContext::getFunctionTypeInternal(
5114 QualType ResultTy, ArrayRef<QualType> ArgArray,
5115 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
5116 size_t NumArgs = ArgArray.size();
5117
5118 // Unique functions, to guarantee there is only one function of a particular
5119 // structure.
5120 llvm::FoldingSetNodeID ID;
5121 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
5122 *this);
5123
5124 QualType Canonical;
5125 bool Unique = false;
5126
5127 llvm::FoldingSetInsertToken Token;
5128 if (FunctionProtoType *FPT = FunctionProtoTypes.lookup(ID, Token)) {
5129 QualType Existing = QualType(FPT, 0);
5130
5131 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
5132 // it so long as our exception specification doesn't contain a dependent
5133 // noexcept expression, or we're just looking for a canonical type.
5134 // Otherwise, we're going to need to create a type
5135 // sugar node to hold the concrete expression.
5136 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
5137 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
5138 return Existing;
5139
5140 // We need a new type sugar node for this one, to hold the new noexcept
5141 // expression. We do no canonicalization here, but that's OK since we don't
5142 // expect to see the same noexcept expression much more than once.
5143 Canonical = getCanonicalType(Existing);
5144 Unique = true;
5145 }
5146
5147 bool NoexceptInType = getLangOpts().CPlusPlus17;
5148 bool IsCanonicalExceptionSpec =
5150
5151 // Determine whether the type being created is already canonical or not.
5152 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
5153 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
5154 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
5155 if (!ArgArray[i].isCanonicalAsParam())
5156 isCanonical = false;
5157
5158 if (OnlyWantCanonical)
5159 assert(isCanonical &&
5160 "given non-canonical parameters constructing canonical type");
5161
5162 // If this type isn't canonical, get the canonical version of it if we don't
5163 // already have it. The exception spec is only partially part of the
5164 // canonical type, and only in C++17 onwards.
5165 if (!isCanonical && Canonical.isNull()) {
5166 SmallVector<QualType, 16> CanonicalArgs;
5167 CanonicalArgs.reserve(NumArgs);
5168 for (unsigned i = 0; i != NumArgs; ++i)
5169 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
5170
5171 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
5172 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
5173 CanonicalEPI.HasTrailingReturn = false;
5174
5175 if (IsCanonicalExceptionSpec) {
5176 // Exception spec is already OK.
5177 } else if (NoexceptInType) {
5178 switch (EPI.ExceptionSpec.Type) {
5180 // We don't know yet. It shouldn't matter what we pick here; no-one
5181 // should ever look at this.
5182 [[fallthrough]];
5183 case EST_None: case EST_MSAny: case EST_NoexceptFalse:
5184 CanonicalEPI.ExceptionSpec.Type = EST_None;
5185 break;
5186
5187 // A dynamic exception specification is almost always "not noexcept",
5188 // with the exception that a pack expansion might expand to no types.
5189 case EST_Dynamic: {
5190 bool AnyPacks = false;
5191 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
5192 if (ET->getAs<PackExpansionType>())
5193 AnyPacks = true;
5194 ExceptionTypeStorage.push_back(getCanonicalType(ET));
5195 }
5196 if (!AnyPacks)
5197 CanonicalEPI.ExceptionSpec.Type = EST_None;
5198 else {
5199 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
5200 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
5201 }
5202 break;
5203 }
5204
5205 case EST_DynamicNone:
5206 case EST_BasicNoexcept:
5207 case EST_NoexceptTrue:
5208 case EST_NoThrow:
5209 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
5210 break;
5211
5213 llvm_unreachable("dependent noexcept is already canonical");
5214 }
5215 } else {
5216 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
5217 }
5218
5219 // Adjust the canonical function result type.
5220 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
5221 Canonical =
5222 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
5223
5224 // Get the new insert position for the node we care about.
5225 FunctionProtoType *NewIP = FunctionProtoTypes.lookup(ID, Token);
5226 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
5227 }
5228
5229 // Compute the needed size to hold this FunctionProtoType and the
5230 // various trailing objects.
5231 auto ESH = FunctionProtoType::getExceptionSpecSize(
5232 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
5233 size_t Size = FunctionProtoType::totalSizeToAlloc<
5234 QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields,
5235 FunctionType::FunctionTypeExtraAttributeInfo,
5236 FunctionType::FunctionTypeArmAttributes, FunctionType::ExceptionType,
5237 Expr *, FunctionDecl *, FunctionProtoType::ExtParameterInfo, Qualifiers,
5238 FunctionEffect, EffectConditionExpr>(
5241 EPI.requiresFunctionProtoTypeArmAttributes(), ESH.NumExceptionType,
5242 ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
5243 EPI.ExtParameterInfos ? NumArgs : 0,
5245 EPI.FunctionEffects.conditions().size());
5246
5247 auto *FTP = (FunctionProtoType *)Allocate(Size, alignof(FunctionProtoType));
5248 FunctionProtoType::ExtProtoInfo newEPI = EPI;
5249 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
5250 Types.push_back(FTP);
5251 if (!Unique)
5252 FunctionProtoTypes.insert(FTP, Token);
5253 if (!EPI.FunctionEffects.empty())
5254 AnyFunctionEffects = true;
5255 return QualType(FTP, 0);
5256}
5257
5258QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
5259 llvm::FoldingSetInsertToken Token;
5260 if (PipeType *PT = PipeTypes.lookup({T, ReadOnly}, Token))
5261 return QualType(PT, 0);
5262
5263 // If the pipe element type isn't canonical, this won't be a canonical type
5264 // either, so fill in the canonical type field.
5265 QualType Canonical;
5266 if (!T.isCanonical()) {
5267 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
5268
5269 assert(!PipeTypes.lookup({T, ReadOnly}, Token) &&
5270 "Shouldn't be in the map!");
5271 }
5272 auto *New = new (*this, alignof(PipeType)) PipeType(T, Canonical, ReadOnly);
5273 Types.push_back(New);
5274 PipeTypes.insert(New, Token);
5275 return QualType(New, 0);
5276}
5277
5279 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
5280 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
5281 : Ty;
5282}
5283
5285 return getPipeType(T, true);
5286}
5287
5289 return getPipeType(T, false);
5290}
5291
5292QualType ASTContext::getBitIntType(bool IsUnsigned, unsigned NumBits) const {
5293 auto Key = std::make_pair(unsigned(IsUnsigned), NumBits);
5294
5295 llvm::FoldingSetInsertToken Token;
5296 if (BitIntType *EIT = BitIntTypes.lookup(Key, Token))
5297 return QualType(EIT, 0);
5298
5299 auto *New = new (*this, alignof(BitIntType)) BitIntType(IsUnsigned, NumBits);
5300 BitIntTypes.insert(New, Token);
5301 Types.push_back(New);
5302 return QualType(New, 0);
5303}
5304
5306 Expr *NumBitsExpr) const {
5307 assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent");
5308 llvm::FoldingSetNodeID ID;
5309 DependentBitIntType::Profile(ID, *this, IsUnsigned, NumBitsExpr);
5310
5311 llvm::FoldingSetInsertToken Token;
5312 if (DependentBitIntType *Existing = DependentBitIntTypes.lookup(ID, Token))
5313 return QualType(Existing, 0);
5314
5315 auto *New = new (*this, alignof(DependentBitIntType))
5316 DependentBitIntType(IsUnsigned, NumBitsExpr);
5317 DependentBitIntTypes.insert(New, Token);
5318
5319 Types.push_back(New);
5320 return QualType(New, 0);
5321}
5322
5325 using Kind = PredefinedSugarType::Kind;
5326
5327 if (auto *Target = PredefinedSugarTypes[llvm::to_underlying(KD)];
5328 Target != nullptr)
5329 return QualType(Target, 0);
5330
5331 auto getCanonicalType = [](const ASTContext &Ctx, Kind KDI) -> QualType {
5332 switch (KDI) {
5333 // size_t (C99TC3 6.5.3.4), signed size_t (C++23 5.13.2) and
5334 // ptrdiff_t (C99TC3 6.5.6) Although these types are not built-in, they
5335 // are part of the core language and are widely used. Using
5336 // PredefinedSugarType makes these types as named sugar types rather than
5337 // standard integer types, enabling better hints and diagnostics.
5338 case Kind::SizeT:
5339 return Ctx.getFromTargetType(Ctx.Target->getSizeType());
5340 case Kind::SignedSizeT:
5341 return Ctx.getFromTargetType(Ctx.Target->getSignedSizeType());
5342 case Kind::PtrdiffT:
5343 return Ctx.getFromTargetType(Ctx.Target->getPtrDiffType(LangAS::Default));
5344 }
5345 llvm_unreachable("unexpected kind");
5346 };
5347 auto *New = new (*this, alignof(PredefinedSugarType))
5348 PredefinedSugarType(KD, &Idents.get(PredefinedSugarType::getName(KD)),
5349 getCanonicalType(*this, static_cast<Kind>(KD)));
5350 Types.push_back(New);
5351 PredefinedSugarTypes[llvm::to_underlying(KD)] = New;
5352 return QualType(New, 0);
5353}
5354
5356 NestedNameSpecifier Qualifier,
5357 const TypeDecl *Decl) const {
5358 if (auto *Tag = dyn_cast<TagDecl>(Decl))
5359 return getTagType(Keyword, Qualifier, Tag,
5360 /*OwnsTag=*/false);
5361 if (auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
5362 return getTypedefType(Keyword, Qualifier, Typedef);
5363 if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(Decl))
5364 return getUnresolvedUsingType(Keyword, Qualifier, UD);
5365
5367 assert(!Qualifier);
5368 return QualType(Decl->TypeForDecl, 0);
5369}
5370
5372 if (auto *Tag = dyn_cast<TagDecl>(TD))
5373 return getCanonicalTagType(Tag);
5374 if (auto *TN = dyn_cast<TypedefNameDecl>(TD))
5375 return getCanonicalType(TN->getUnderlyingType());
5376 if (const auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(TD))
5378 assert(TD->TypeForDecl);
5379 return TD->TypeForDecl->getCanonicalTypeUnqualified();
5380}
5381
5383 if (const auto *TD = dyn_cast<TagDecl>(Decl))
5384 return getCanonicalTagType(TD);
5385 if (const auto *TD = dyn_cast<TypedefNameDecl>(Decl);
5386 isa_and_nonnull<TypedefDecl, TypeAliasDecl>(TD))
5388 /*Qualifier=*/std::nullopt, TD);
5389 if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl))
5390 return getCanonicalUnresolvedUsingType(Using);
5391
5392 assert(Decl->TypeForDecl);
5393 return QualType(Decl->TypeForDecl, 0);
5394}
5395
5396/// getTypedefType - Return the unique reference to the type for the
5397/// specified typedef name decl.
5400 NestedNameSpecifier Qualifier,
5401 const TypedefNameDecl *Decl, QualType UnderlyingType,
5402 std::optional<bool> TypeMatchesDeclOrNone) const {
5403 if (!TypeMatchesDeclOrNone) {
5404 QualType DeclUnderlyingType = Decl->getUnderlyingType();
5405 assert(!DeclUnderlyingType.isNull());
5406 if (UnderlyingType.isNull())
5407 UnderlyingType = DeclUnderlyingType;
5408 else
5409 assert(hasSameType(UnderlyingType, DeclUnderlyingType));
5410 TypeMatchesDeclOrNone = UnderlyingType == DeclUnderlyingType;
5411 } else {
5412 // FIXME: This is a workaround for a serialization cycle: assume the decl
5413 // underlying type is not available; don't touch it.
5414 assert(!UnderlyingType.isNull());
5415 }
5416
5417 if (Keyword == ElaboratedTypeKeyword::None && !Qualifier &&
5418 *TypeMatchesDeclOrNone) {
5419 if (Decl->TypeForDecl)
5420 return QualType(Decl->TypeForDecl, 0);
5421
5422 auto *NewType = new (*this, alignof(TypedefType))
5423 TypedefType(Type::Typedef, Keyword, Qualifier, Decl, UnderlyingType,
5424 !*TypeMatchesDeclOrNone);
5425
5426 Types.push_back(NewType);
5427 Decl->TypeForDecl = NewType;
5428 return QualType(NewType, 0);
5429 }
5430
5431 llvm::FoldingSetNodeID ID;
5432 TypedefType::Profile(ID, Keyword, Qualifier, Decl,
5433 *TypeMatchesDeclOrNone ? QualType() : UnderlyingType);
5434
5435 llvm::FoldingSetInsertToken Token;
5436 if (FoldingSetPlaceholder<TypedefType> *Placeholder =
5437 TypedefTypes.lookup(ID, Token))
5438 return QualType(Placeholder->getType(), 0);
5439
5440 void *Mem =
5441 Allocate(TypedefType::totalSizeToAlloc<FoldingSetPlaceholder<TypedefType>,
5443 1, !!Qualifier, !*TypeMatchesDeclOrNone),
5444 alignof(TypedefType));
5445 auto *NewType =
5446 new (Mem) TypedefType(Type::Typedef, Keyword, Qualifier, Decl,
5447 UnderlyingType, !*TypeMatchesDeclOrNone);
5448 auto *Placeholder = new (NewType->getFoldingSetPlaceholder())
5450 TypedefTypes.insert(Placeholder, Token);
5451 Types.push_back(NewType);
5452 return QualType(NewType, 0);
5453}
5454
5456 NestedNameSpecifier Qualifier,
5457 const UsingShadowDecl *D,
5458 QualType UnderlyingType) const {
5459 // FIXME: This is expensive to compute every time!
5460 if (UnderlyingType.isNull()) {
5461 const auto *UD = cast<UsingDecl>(D->getIntroducer());
5462 UnderlyingType =
5465 UD->getQualifier(), cast<TypeDecl>(D->getTargetDecl()));
5466 }
5467
5468 llvm::FoldingSetNodeID ID;
5469 UsingType::Profile(ID, Keyword, Qualifier, D, UnderlyingType);
5470
5471 llvm::FoldingSetInsertToken Token;
5472 if (const UsingType *T = UsingTypes.lookup(ID, Token))
5473 return QualType(T, 0);
5474
5475 assert(!UnderlyingType.hasLocalQualifiers());
5476
5477 assert(
5479 UnderlyingType));
5480
5481 void *Mem =
5482 Allocate(UsingType::totalSizeToAlloc<NestedNameSpecifier>(!!Qualifier),
5483 alignof(UsingType));
5484 UsingType *T = new (Mem) UsingType(Keyword, Qualifier, D, UnderlyingType);
5485 Types.push_back(T);
5486 UsingTypes.insert(T, Token);
5487 return QualType(T, 0);
5488}
5489
5490TagType *ASTContext::getTagTypeInternal(ElaboratedTypeKeyword Keyword,
5491 NestedNameSpecifier Qualifier,
5492 const TagDecl *TD, bool OwnsTag,
5493 bool IsInjected,
5494 const Type *CanonicalType,
5495 bool WithFoldingSetNode) const {
5496 auto [TC, Size] = [&] {
5497 switch (TD->getDeclKind()) {
5498 case Decl::Enum:
5499 static_assert(alignof(EnumType) == alignof(TagType));
5500 return std::make_tuple(Type::Enum, sizeof(EnumType));
5501 case Decl::ClassTemplatePartialSpecialization:
5502 case Decl::ClassTemplateSpecialization:
5503 case Decl::CXXRecord:
5504 static_assert(alignof(RecordType) == alignof(TagType));
5505 static_assert(alignof(InjectedClassNameType) == alignof(TagType));
5506 if (cast<CXXRecordDecl>(TD)->hasInjectedClassType())
5507 return std::make_tuple(Type::InjectedClassName,
5508 sizeof(InjectedClassNameType));
5509 [[fallthrough]];
5510 case Decl::Record:
5511 return std::make_tuple(Type::Record, sizeof(RecordType));
5512 default:
5513 llvm_unreachable("unexpected decl kind");
5514 }
5515 }();
5516
5517 if (Qualifier) {
5518 static_assert(alignof(NestedNameSpecifier) <= alignof(TagType));
5519 Size = llvm::alignTo(Size, alignof(NestedNameSpecifier)) +
5520 sizeof(NestedNameSpecifier);
5521 }
5522 void *Mem;
5523 if (WithFoldingSetNode) {
5524 // FIXME: It would be more profitable to tail allocate the folding set node
5525 // from the type, instead of the other way around, due to the greater
5526 // alignment requirements of the type. But this makes it harder to deal with
5527 // the different type node sizes. This would require either uniquing from
5528 // different folding sets, or having the folding setaccept a
5529 // contextual parameter which is not fixed at construction.
5530 Mem = Allocate(
5531 sizeof(TagTypeFoldingSetPlaceholder) +
5532 TagTypeFoldingSetPlaceholder::getOffset() + Size,
5533 std::max(alignof(TagTypeFoldingSetPlaceholder), alignof(TagType)));
5534 auto *T = new (Mem) TagTypeFoldingSetPlaceholder();
5535 Mem = T->getTagType();
5536 } else {
5537 Mem = Allocate(Size, alignof(TagType));
5538 }
5539
5540 auto *T = [&, TC = TC]() -> TagType * {
5541 switch (TC) {
5542 case Type::Enum: {
5543 assert(isa<EnumDecl>(TD));
5544 auto *T = new (Mem) EnumType(TC, Keyword, Qualifier, TD, OwnsTag,
5545 IsInjected, CanonicalType);
5546 assert(reinterpret_cast<void *>(T) ==
5547 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5548 "TagType must be the first base of EnumType");
5549 return T;
5550 }
5551 case Type::Record: {
5552 assert(isa<RecordDecl>(TD));
5553 auto *T = new (Mem) RecordType(TC, Keyword, Qualifier, TD, OwnsTag,
5554 IsInjected, CanonicalType);
5555 assert(reinterpret_cast<void *>(T) ==
5556 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5557 "TagType must be the first base of RecordType");
5558 return T;
5559 }
5560 case Type::InjectedClassName: {
5561 auto *T = new (Mem) InjectedClassNameType(Keyword, Qualifier, TD,
5562 IsInjected, CanonicalType);
5563 assert(reinterpret_cast<void *>(T) ==
5564 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5565 "TagType must be the first base of InjectedClassNameType");
5566 return T;
5567 }
5568 default:
5569 llvm_unreachable("unexpected type class");
5570 }
5571 }();
5572 assert(T->getKeyword() == Keyword);
5573 assert(T->getQualifier() == Qualifier);
5574 assert(T->getDecl() == TD);
5575 assert(T->isInjected() == IsInjected);
5576 assert(T->isTagOwned() == OwnsTag);
5577 assert((T->isCanonicalUnqualified()
5578 ? QualType()
5579 : T->getCanonicalTypeInternal()) == QualType(CanonicalType, 0));
5580 Types.push_back(T);
5581 return T;
5582}
5583
5584static const TagDecl *getNonInjectedClassName(const TagDecl *TD) {
5585 if (const auto *RD = dyn_cast<CXXRecordDecl>(TD);
5586 RD && RD->isInjectedClassName())
5587 return cast<TagDecl>(RD->getDeclContext());
5588 return TD;
5589}
5590
5593 if (TD->TypeForDecl)
5594 return TD->TypeForDecl->getCanonicalTypeUnqualified();
5595
5596 const Type *CanonicalType = getTagTypeInternal(
5598 /*Qualifier=*/std::nullopt, TD,
5599 /*OwnsTag=*/false, /*IsInjected=*/false, /*CanonicalType=*/nullptr,
5600 /*WithFoldingSetNode=*/false);
5601 TD->TypeForDecl = CanonicalType;
5602 return CanQualType::CreateUnsafe(QualType(CanonicalType, 0));
5603}
5604
5606 NestedNameSpecifier Qualifier,
5607 const TagDecl *TD, bool OwnsTag) const {
5608
5609 const TagDecl *NonInjectedTD = ::getNonInjectedClassName(TD);
5610 bool IsInjected = TD != NonInjectedTD;
5611
5612 ElaboratedTypeKeyword PreferredKeyword =
5615 NonInjectedTD->getTagKind());
5616
5617 if (Keyword == PreferredKeyword && !Qualifier && !OwnsTag) {
5618 if (const Type *T = TD->TypeForDecl; T && !T->isCanonicalUnqualified())
5619 return QualType(T, 0);
5620
5621 const Type *CanonicalType = getCanonicalTagType(NonInjectedTD).getTypePtr();
5622 const Type *T =
5623 getTagTypeInternal(Keyword,
5624 /*Qualifier=*/std::nullopt, NonInjectedTD,
5625 /*OwnsTag=*/false, IsInjected, CanonicalType,
5626 /*WithFoldingSetNode=*/false);
5627 TD->TypeForDecl = T;
5628 return QualType(T, 0);
5629 }
5630
5631 llvm::FoldingSetNodeID ID;
5632 TagTypeFoldingSetPlaceholder::Profile(ID, Keyword, Qualifier, NonInjectedTD,
5633 OwnsTag, IsInjected);
5634
5635 llvm::FoldingSetInsertToken Token;
5636 if (TagTypeFoldingSetPlaceholder *T = TagTypes.lookup(ID, Token))
5637 return QualType(T->getTagType(), 0);
5638
5639 const Type *CanonicalType = getCanonicalTagType(NonInjectedTD).getTypePtr();
5640 TagType *T =
5641 getTagTypeInternal(Keyword, Qualifier, NonInjectedTD, OwnsTag, IsInjected,
5642 CanonicalType, /*WithFoldingSetNode=*/true);
5643 TagTypes.insert(TagTypeFoldingSetPlaceholder::fromTagType(T), Token);
5644 return QualType(T, 0);
5645}
5646
5647bool ASTContext::computeBestEnumTypes(bool IsPacked, unsigned NumNegativeBits,
5648 unsigned NumPositiveBits,
5649 QualType &BestType,
5650 QualType &BestPromotionType) {
5651 unsigned IntWidth = Target->getIntWidth();
5652 unsigned CharWidth = Target->getCharWidth();
5653 unsigned ShortWidth = Target->getShortWidth();
5654 bool EnumTooLarge = false;
5655 unsigned BestWidth;
5656 if (NumNegativeBits) {
5657 // If there is a negative value, figure out the smallest integer type (of
5658 // int/long/longlong) that fits.
5659 // If it's packed, check also if it fits a char or a short.
5660 if (IsPacked && NumNegativeBits <= CharWidth &&
5661 NumPositiveBits < CharWidth) {
5662 BestType = SignedCharTy;
5663 BestWidth = CharWidth;
5664 } else if (IsPacked && NumNegativeBits <= ShortWidth &&
5665 NumPositiveBits < ShortWidth) {
5666 BestType = ShortTy;
5667 BestWidth = ShortWidth;
5668 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
5669 BestType = IntTy;
5670 BestWidth = IntWidth;
5671 } else {
5672 BestWidth = Target->getLongWidth();
5673
5674 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
5675 BestType = LongTy;
5676 } else {
5677 BestWidth = Target->getLongLongWidth();
5678
5679 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
5680 EnumTooLarge = true;
5681 BestType = LongLongTy;
5682 }
5683 }
5684 BestPromotionType = (BestWidth <= IntWidth ? IntTy : BestType);
5685 } else {
5686 // If there is no negative value, figure out the smallest type that fits
5687 // all of the enumerator values.
5688 // If it's packed, check also if it fits a char or a short.
5689 if (IsPacked && NumPositiveBits <= CharWidth) {
5690 BestType = UnsignedCharTy;
5691 BestPromotionType = IntTy;
5692 BestWidth = CharWidth;
5693 } else if (IsPacked && NumPositiveBits <= ShortWidth) {
5694 BestType = UnsignedShortTy;
5695 BestPromotionType = IntTy;
5696 BestWidth = ShortWidth;
5697 } else if (NumPositiveBits <= IntWidth) {
5698 BestType = UnsignedIntTy;
5699 BestWidth = IntWidth;
5700 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5702 : IntTy;
5703 } else if (NumPositiveBits <= (BestWidth = Target->getLongWidth())) {
5704 BestType = UnsignedLongTy;
5705 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5707 : LongTy;
5708 } else {
5709 BestWidth = Target->getLongLongWidth();
5710 if (NumPositiveBits > BestWidth) {
5711 // This can happen with bit-precise integer types, but those are not
5712 // allowed as the type for an enumerator per C23 6.7.2.2p4 and p12.
5713 // FIXME: GCC uses __int128_t and __uint128_t for cases that fit within
5714 // a 128-bit integer, we should consider doing the same.
5715 EnumTooLarge = true;
5716 }
5717 BestType = UnsignedLongLongTy;
5718 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5720 : LongLongTy;
5721 }
5722 }
5723 return EnumTooLarge;
5724}
5725
5727 assert((T->isIntegralType(*this) || T->isEnumeralType()) &&
5728 "Integral type required!");
5729 unsigned BitWidth = getIntWidth(T);
5730
5731 if (Value.isUnsigned() || Value.isNonNegative()) {
5732 if (T->isSignedIntegerOrEnumerationType())
5733 --BitWidth;
5734 return Value.getActiveBits() <= BitWidth;
5735 }
5736 return Value.getSignificantBits() <= BitWidth;
5737}
5738
5739UnresolvedUsingType *ASTContext::getUnresolvedUsingTypeInternal(
5741 const UnresolvedUsingTypenameDecl *D, llvm::FoldingSetInsertToken Token,
5742 const Type *CanonicalType) const {
5743 void *Mem = Allocate(
5744 UnresolvedUsingType::totalSizeToAlloc<
5746 !!Token, !!Qualifier),
5747 alignof(UnresolvedUsingType));
5748 auto *T = new (Mem) UnresolvedUsingType(Keyword, Qualifier, D, CanonicalType);
5749 if (Token) {
5750 auto *Placeholder = new (T->getFoldingSetPlaceholder())
5752 UnresolvedUsingTypes.insert(Placeholder, Token);
5753 }
5754 Types.push_back(T);
5755 return T;
5756}
5757
5759 const UnresolvedUsingTypenameDecl *D) const {
5760 D = D->getCanonicalDecl();
5761 if (D->TypeForDecl)
5762 return D->TypeForDecl->getCanonicalTypeUnqualified();
5763
5764 const Type *CanonicalType =
5765 getUnresolvedUsingTypeInternal(ElaboratedTypeKeyword::None,
5766 /*Qualifier=*/std::nullopt, D,
5767 /*Token=*/{}, /*CanonicalType=*/nullptr);
5768 D->TypeForDecl = CanonicalType;
5769 return CanQualType::CreateUnsafe(QualType(CanonicalType, 0));
5770}
5771
5774 NestedNameSpecifier Qualifier,
5775 const UnresolvedUsingTypenameDecl *D) const {
5776 if (Keyword == ElaboratedTypeKeyword::None && !Qualifier) {
5777 if (const Type *T = D->TypeForDecl; T && !T->isCanonicalUnqualified())
5778 return QualType(T, 0);
5779
5780 const Type *CanonicalType = getCanonicalUnresolvedUsingType(D).getTypePtr();
5781 const Type *T =
5782 getUnresolvedUsingTypeInternal(ElaboratedTypeKeyword::None,
5783 /*Qualifier=*/std::nullopt, D,
5784 /*Token=*/{}, CanonicalType);
5785 D->TypeForDecl = T;
5786 return QualType(T, 0);
5787 }
5788
5789 llvm::FoldingSetNodeID ID;
5790 UnresolvedUsingType::Profile(ID, Keyword, Qualifier, D);
5791
5792 llvm::FoldingSetInsertToken Token;
5794 UnresolvedUsingTypes.lookup(ID, Token))
5795 return QualType(Placeholder->getType(), 0);
5796 assert(Token);
5797
5798 const Type *CanonicalType = getCanonicalUnresolvedUsingType(D).getTypePtr();
5799 const Type *T = getUnresolvedUsingTypeInternal(Keyword, Qualifier, D, Token,
5800 CanonicalType);
5801 return QualType(T, 0);
5802}
5803
5805 QualType modifiedType,
5806 QualType equivalentType,
5807 const Attr *attr) const {
5808 llvm::FoldingSetNodeID id;
5809 AttributedType::Profile(id, *this, attrKind, modifiedType, equivalentType,
5810 attr);
5811
5812 llvm::FoldingSetInsertToken Token;
5813 AttributedType *type = AttributedTypes.lookup(id, Token);
5814 if (type) return QualType(type, 0);
5815
5816 assert(!attr || attr->getKind() == attrKind);
5817
5818 QualType canon = getCanonicalType(equivalentType);
5819 type = new (*this, alignof(AttributedType))
5820 AttributedType(canon, attrKind, attr, modifiedType, equivalentType);
5821
5822 Types.push_back(type);
5823 AttributedTypes.insert(type, Token);
5824
5825 return QualType(type, 0);
5826}
5827
5829 QualType equivalentType) const {
5830 return getAttributedType(attr->getKind(), modifiedType, equivalentType, attr);
5831}
5832
5834 QualType modifiedType,
5835 QualType equivalentType) const {
5836 switch (nullability) {
5838 return getAttributedType(attr::TypeNonNull, modifiedType, equivalentType);
5839
5841 return getAttributedType(attr::TypeNullable, modifiedType, equivalentType);
5842
5844 return getAttributedType(attr::TypeNullableResult, modifiedType,
5845 equivalentType);
5846
5848 return getAttributedType(attr::TypeNullUnspecified, modifiedType,
5849 equivalentType);
5850 }
5851
5852 llvm_unreachable("Unknown nullability kind");
5853}
5854
5855QualType ASTContext::getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
5856 QualType Wrapped) const {
5857 llvm::FoldingSetNodeID ID;
5858 BTFTagAttributedType::Profile(ID, Wrapped, BTFAttr);
5859
5860 llvm::FoldingSetInsertToken Token;
5861 BTFTagAttributedType *Ty = BTFTagAttributedTypes.lookup(ID, Token);
5862 if (Ty)
5863 return QualType(Ty, 0);
5864
5865 QualType Canon = getCanonicalType(Wrapped);
5866 Ty = new (*this, alignof(BTFTagAttributedType))
5867 BTFTagAttributedType(Canon, Wrapped, BTFAttr);
5868
5869 Types.push_back(Ty);
5870 BTFTagAttributedTypes.insert(Ty, Token);
5871
5872 return QualType(Ty, 0);
5873}
5874
5876 QualType Underlying) const {
5877 const IdentifierInfo *II = Attr->getBehaviorKind();
5878 StringRef IdentName = II->getName();
5879 OverflowBehaviorType::OverflowBehaviorKind Kind;
5880 if (IdentName == "wrap") {
5881 Kind = OverflowBehaviorType::OverflowBehaviorKind::Wrap;
5882 } else if (IdentName == "trap") {
5883 Kind = OverflowBehaviorType::OverflowBehaviorKind::Trap;
5884 } else {
5885 return Underlying;
5886 }
5887
5888 return getOverflowBehaviorType(Kind, Underlying);
5889}
5890
5892 OverflowBehaviorType::OverflowBehaviorKind Kind,
5893 QualType Underlying) const {
5894 assert(!Underlying->isOverflowBehaviorType() &&
5895 "Cannot have underlying types that are themselves OBTs");
5896
5897 llvm::FoldingSetInsertToken Token;
5898 if (OverflowBehaviorType *OBT =
5899 OverflowBehaviorTypes.lookup({Underlying, Kind}, Token)) {
5900 return QualType(OBT, 0);
5901 }
5902
5903 QualType Canonical;
5904 if (!Underlying.isCanonical() || Underlying.hasLocalQualifiers()) {
5905 SplitQualType canonSplit = getCanonicalType(Underlying).split();
5906 Canonical = getOverflowBehaviorType(Kind, QualType(canonSplit.Ty, 0));
5907 Canonical = getQualifiedType(Canonical, canonSplit.Quals);
5908 assert(!OverflowBehaviorTypes.lookup({Underlying, Kind}, Token) &&
5909 "Shouldn't be in the map");
5910 }
5911
5912 OverflowBehaviorType *Ty = new (*this, alignof(OverflowBehaviorType))
5913 OverflowBehaviorType(*this, Canonical, Underlying, Kind);
5914
5915 Types.push_back(Ty);
5916 OverflowBehaviorTypes.insert(Ty, Token);
5917 return QualType(Ty, 0);
5918}
5919
5921 QualType Wrapped, QualType Contained,
5922 const HLSLAttributedResourceType::Attributes &Attrs) {
5923
5924 llvm::FoldingSetNodeID ID;
5925 HLSLAttributedResourceType::Profile(ID, *this, Wrapped, Contained, Attrs);
5926
5927 llvm::FoldingSetInsertToken Token;
5928 HLSLAttributedResourceType *Ty =
5929 HLSLAttributedResourceTypes.lookup(ID, Token);
5930 if (Ty)
5931 return QualType(Ty, 0);
5932
5933 Ty = new (*this, alignof(HLSLAttributedResourceType))
5934 HLSLAttributedResourceType(Wrapped, Contained, Attrs);
5935
5936 Types.push_back(Ty);
5937 HLSLAttributedResourceTypes.insert(Ty, Token);
5938
5939 return QualType(Ty, 0);
5940}
5941
5942QualType ASTContext::getHLSLInlineSpirvType(uint32_t Opcode, uint32_t Size,
5943 uint32_t Alignment,
5944 ArrayRef<SpirvOperand> Operands) {
5945 llvm::FoldingSetNodeID ID;
5946 HLSLInlineSpirvType::Profile(ID, Opcode, Size, Alignment, Operands);
5947
5948 llvm::FoldingSetInsertToken Token;
5949 HLSLInlineSpirvType *Ty = HLSLInlineSpirvTypes.lookup(ID, Token);
5950 if (Ty)
5951 return QualType(Ty, 0);
5952
5953 void *Mem = Allocate(
5954 HLSLInlineSpirvType::totalSizeToAlloc<SpirvOperand>(Operands.size()),
5955 alignof(HLSLInlineSpirvType));
5956
5957 Ty = new (Mem) HLSLInlineSpirvType(Opcode, Size, Alignment, Operands);
5958
5959 Types.push_back(Ty);
5960 HLSLInlineSpirvTypes.insert(Ty, Token);
5961
5962 return QualType(Ty, 0);
5963}
5964
5965/// Retrieve a substitution-result type.
5967 Decl *AssociatedDecl,
5968 unsigned Index,
5970 bool Final) const {
5971 auto Key =
5972 std::make_tuple(Replacement, AssociatedDecl, Index,
5973 PackIndex.toInternalRepresentation(), unsigned(Final));
5974 llvm::FoldingSetInsertToken Token;
5975 SubstTemplateTypeParmType *SubstParm =
5976 SubstTemplateTypeParmTypes.lookup(Key, Token);
5977
5978 if (!SubstParm) {
5979 void *Mem = Allocate(SubstTemplateTypeParmType::totalSizeToAlloc<QualType>(
5980 !Replacement.isCanonical()),
5981 alignof(SubstTemplateTypeParmType));
5982 SubstParm = new (Mem) SubstTemplateTypeParmType(Replacement, AssociatedDecl,
5983 Index, PackIndex, Final);
5984 Types.push_back(SubstParm);
5985 SubstTemplateTypeParmTypes.insert(SubstParm, Token);
5986 }
5987
5988 return QualType(SubstParm, 0);
5989}
5990
5993 unsigned Index, bool Final,
5994 const TemplateArgument &ArgPack) {
5995#ifndef NDEBUG
5996 for (const auto &P : ArgPack.pack_elements())
5997 assert(P.getKind() == TemplateArgument::Type && "Pack contains a non-type");
5998#endif
5999
6000 llvm::FoldingSetNodeID ID;
6001 SubstTemplateTypeParmPackType::Profile(ID, AssociatedDecl, Index, Final,
6002 ArgPack);
6003 llvm::FoldingSetInsertToken Token;
6004 if (SubstTemplateTypeParmPackType *SubstParm =
6005 SubstTemplateTypeParmPackTypes.lookup(ID, Token))
6006 return QualType(SubstParm, 0);
6007
6008 QualType Canon;
6009 {
6010 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(ArgPack);
6011 if (!AssociatedDecl->isCanonicalDecl() ||
6012 !CanonArgPack.structurallyEquals(ArgPack)) {
6014 AssociatedDecl->getCanonicalDecl(), Index, Final, CanonArgPack);
6015 [[maybe_unused]] const auto *Nothing =
6016 SubstTemplateTypeParmPackTypes.lookup(ID, Token);
6017 assert(!Nothing);
6018 }
6019 }
6020
6021 auto *SubstParm = new (*this, alignof(SubstTemplateTypeParmPackType))
6022 SubstTemplateTypeParmPackType(Canon, AssociatedDecl, Index, Final,
6023 ArgPack);
6024 Types.push_back(SubstParm);
6025 SubstTemplateTypeParmPackTypes.insert(SubstParm, Token);
6026 return QualType(SubstParm, 0);
6027}
6028
6031 assert(llvm::all_of(ArgPack.pack_elements(),
6032 [](const auto &P) {
6033 return P.getKind() == TemplateArgument::Type;
6034 }) &&
6035 "Pack contains a non-type");
6036
6037 llvm::FoldingSetNodeID ID;
6038 SubstBuiltinTemplatePackType::Profile(ID, ArgPack);
6039
6040 llvm::FoldingSetInsertToken Token;
6041 if (auto *T = SubstBuiltinTemplatePackTypes.lookup(ID, Token))
6042 return QualType(T, 0);
6043
6044 QualType Canon;
6045 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(ArgPack);
6046 if (!CanonArgPack.structurallyEquals(ArgPack)) {
6047 Canon = getSubstBuiltinTemplatePack(CanonArgPack);
6048 // Refresh Token, in case the recursive call above caused rehashing,
6049 // which would invalidate the bucket pointer.
6050 [[maybe_unused]] const auto *Nothing =
6051 SubstBuiltinTemplatePackTypes.lookup(ID, Token);
6052 assert(!Nothing);
6053 }
6054
6055 auto *PackType = new (*this, alignof(SubstBuiltinTemplatePackType))
6056 SubstBuiltinTemplatePackType(Canon, ArgPack);
6057 Types.push_back(PackType);
6058 SubstBuiltinTemplatePackTypes.insert(PackType, Token);
6059 return QualType(PackType, 0);
6060}
6061
6062/// Retrieve the template type parameter type for a template
6063/// parameter or parameter pack with the given depth, index, and (optionally)
6064/// name.
6066ASTContext::getTemplateTypeParmType(int Depth, int Index, bool ParameterPack,
6067 TemplateTypeParmDecl *TTPDecl) const {
6068 assert(Depth >= 0 && "Depth must be non-negative");
6069 assert(Index >= 0 && "Index must be non-negative");
6070
6071 auto Key = std::make_tuple(unsigned(Depth), unsigned(Index),
6072 unsigned(ParameterPack), TTPDecl);
6073 llvm::FoldingSetInsertToken Token;
6074 TemplateTypeParmType *TypeParm = TemplateTypeParmTypes.lookup(Key, Token);
6075
6076 if (TypeParm)
6077 return QualType(TypeParm, 0);
6078
6079 if (TTPDecl) {
6080 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
6081 TypeParm = new (*this, alignof(TemplateTypeParmType))
6082 TemplateTypeParmType(Depth, Index, ParameterPack, TTPDecl, Canon);
6083 } else
6084 TypeParm = new (*this, alignof(TemplateTypeParmType)) TemplateTypeParmType(
6085 Depth, Index, ParameterPack, /*TTPDecl=*/nullptr, /*Canon=*/QualType());
6086
6087 Types.push_back(TypeParm);
6088 TemplateTypeParmTypes.insert(TypeParm, Token);
6089
6090 return QualType(TypeParm, 0);
6091}
6092
6095 switch (Keyword) {
6096 // These are just themselves.
6102 return Keyword;
6103
6104 // These are equivalent.
6107
6108 // These are functionally equivalent, so relying on their equivalence is
6109 // IFNDR. By making them equivalent, we disallow overloading, which at least
6110 // can produce a diagnostic.
6113 }
6114 llvm_unreachable("unexpected keyword kind");
6115}
6116
6118 ElaboratedTypeKeyword Keyword, SourceLocation ElaboratedKeywordLoc,
6119 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKeywordLoc,
6120 TemplateName Name, SourceLocation NameLoc,
6121 const TemplateArgumentListInfo &SpecifiedArgs,
6122 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6124 Keyword, Name, SpecifiedArgs.arguments(), CanonicalArgs, Underlying);
6125
6128 ElaboratedKeywordLoc, QualifierLoc, TemplateKeywordLoc, NameLoc,
6129 SpecifiedArgs);
6130 return TSI;
6131}
6132
6135 ArrayRef<TemplateArgumentLoc> SpecifiedArgs,
6136 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6137 SmallVector<TemplateArgument, 4> SpecifiedArgVec;
6138 SpecifiedArgVec.reserve(SpecifiedArgs.size());
6139 for (const TemplateArgumentLoc &Arg : SpecifiedArgs)
6140 SpecifiedArgVec.push_back(Arg.getArgument());
6141
6142 return getTemplateSpecializationType(Keyword, Template, SpecifiedArgVec,
6143 CanonicalArgs, Underlying);
6144}
6145
6146[[maybe_unused]] static bool
6148 for (const TemplateArgument &Arg : Args)
6149 if (Arg.isPackExpansion())
6150 return true;
6151 return false;
6152}
6153
6156 ArrayRef<TemplateArgument> Args) const {
6157 assert(Template ==
6158 getCanonicalTemplateName(Template, /*IgnoreDeduced=*/true));
6160 Template.getAsDependentTemplateName()));
6161#ifndef NDEBUG
6162 for (const auto &Arg : Args)
6163 assert(Arg.structurallyEquals(getCanonicalTemplateArgument(Arg)));
6164#endif
6165
6166 llvm::FoldingSetNodeID ID;
6167 TemplateSpecializationType::Profile(ID, Keyword, Template, Args, QualType(),
6168 *this);
6169 llvm::FoldingSetInsertToken Token;
6170 if (auto *T = TemplateSpecializationTypes.lookup(ID, Token))
6171 return QualType(T, 0);
6172
6173 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
6174 sizeof(TemplateArgument) * Args.size(),
6175 alignof(TemplateSpecializationType));
6176 auto *Spec =
6177 new (Mem) TemplateSpecializationType(Keyword, Template,
6178 /*IsAlias=*/false, Args, QualType());
6179 assert(Spec->isDependentType() &&
6180 "canonical template specialization must be dependent");
6181 Types.push_back(Spec);
6182 TemplateSpecializationTypes.insert(Spec, Token);
6183 return QualType(Spec, 0);
6184}
6185
6188 ArrayRef<TemplateArgument> SpecifiedArgs,
6189 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6190 const auto *TD = Template.getAsTemplateDecl(/*IgnoreDeduced=*/true);
6191 bool IsTypeAlias = TD && TD->isTypeAlias();
6192 if (Underlying.isNull()) {
6193 TemplateName CanonTemplate =
6194 getCanonicalTemplateName(Template, /*IgnoreDeduced=*/true);
6195 ElaboratedTypeKeyword CanonKeyword =
6196 CanonTemplate.getAsDependentTemplateName()
6199 bool NonCanonical = Template != CanonTemplate || Keyword != CanonKeyword;
6201 if (CanonicalArgs.empty()) {
6202 CanonArgsVec = SmallVector<TemplateArgument, 4>(SpecifiedArgs);
6203 NonCanonical |= canonicalizeTemplateArguments(CanonArgsVec);
6204 CanonicalArgs = CanonArgsVec;
6205 } else {
6206 NonCanonical |= !llvm::equal(
6207 SpecifiedArgs, CanonicalArgs,
6208 [](const TemplateArgument &A, const TemplateArgument &B) {
6209 return A.structurallyEquals(B);
6210 });
6211 }
6212
6213 // We can get here with an alias template when the specialization
6214 // contains a pack expansion that does not match up with a parameter
6215 // pack, or a builtin template which cannot be resolved due to dependency.
6216 assert((!isa_and_nonnull<TypeAliasTemplateDecl>(TD) ||
6217 hasAnyPackExpansions(CanonicalArgs)) &&
6218 "Caller must compute aliased type");
6219 IsTypeAlias = false;
6220
6222 CanonKeyword, CanonTemplate, CanonicalArgs);
6223 if (!NonCanonical)
6224 return Underlying;
6225 }
6226 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
6227 sizeof(TemplateArgument) * SpecifiedArgs.size() +
6228 (IsTypeAlias ? sizeof(QualType) : 0),
6229 alignof(TemplateSpecializationType));
6230 auto *Spec = new (Mem) TemplateSpecializationType(
6231 Keyword, Template, IsTypeAlias, SpecifiedArgs, Underlying);
6232 Types.push_back(Spec);
6233 return QualType(Spec, 0);
6234}
6235
6238 llvm::FoldingSetInsertToken Token;
6239 ParenType *T = ParenTypes.lookup(InnerType, Token);
6240 if (T)
6241 return QualType(T, 0);
6242
6243 QualType Canon = InnerType;
6244 if (!Canon.isCanonical()) {
6245 Canon = getCanonicalType(InnerType);
6246 assert(!ParenTypes.lookup(InnerType, Token) &&
6247 "Paren canonical type broken");
6248 }
6249
6250 T = new (*this, alignof(ParenType)) ParenType(InnerType, Canon);
6251 Types.push_back(T);
6252 ParenTypes.insert(T, Token);
6253 return QualType(T, 0);
6254}
6255
6258 const IdentifierInfo *MacroII) const {
6259 QualType Canon = UnderlyingTy;
6260 if (!Canon.isCanonical())
6261 Canon = getCanonicalType(UnderlyingTy);
6262
6263 auto *newType = new (*this, alignof(MacroQualifiedType))
6264 MacroQualifiedType(UnderlyingTy, Canon, MacroII);
6265 Types.push_back(newType);
6266 return QualType(newType, 0);
6267}
6268
6271 const IdentifierInfo *Name) const {
6272 llvm::FoldingSetNodeID ID;
6273 DependentNameType::Profile(ID, Keyword, NNS, Name);
6274
6275 llvm::FoldingSetInsertToken Token;
6276 if (DependentNameType *T = DependentNameTypes.lookup(ID, Token))
6277 return QualType(T, 0);
6278
6279 ElaboratedTypeKeyword CanonKeyword =
6281 NestedNameSpecifier CanonNNS = NNS.getCanonical();
6282
6283 QualType Canon;
6284 if (CanonKeyword != Keyword || CanonNNS != NNS) {
6285 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
6286 [[maybe_unused]] DependentNameType *T =
6287 DependentNameTypes.lookup(ID, Token);
6288 assert(!T && "broken canonicalization");
6289 assert(Canon.isCanonical());
6290 }
6291
6292 DependentNameType *T = new (*this, alignof(DependentNameType))
6293 DependentNameType(Keyword, NNS, Name, Canon);
6294 Types.push_back(T);
6295 DependentNameTypes.insert(T, Token);
6296 return QualType(T, 0);
6297}
6298
6300 TemplateArgument Arg;
6301 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
6303 if (TTP->isParameterPack())
6304 ArgType = getPackExpansionType(ArgType, std::nullopt);
6305
6307 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
6308 QualType T =
6309 NTTP->getType().getNonPackExpansionType().getNonLValueExprType(*this);
6310 // For class NTTPs, ensure we include the 'const' so the type matches that
6311 // of a real template argument.
6312 // FIXME: It would be more faithful to model this as something like an
6313 // lvalue-to-rvalue conversion applied to a const-qualified lvalue.
6315 if (NTTP->getType()->isReferenceType()) {
6316 // As in Sema::BuildDeclarationNameExpr, a parameter of reference
6317 // type, even an rvalue reference, is an lvalue.
6318 VK = VK_LValue;
6319 } else if (T->isRecordType()) {
6320 // C++ [temp.param]p8: An id-expression naming a non-type
6321 // template-parameter of class type T denotes a static storage duration
6322 // object of type const T.
6323 T.addConst();
6324 VK = VK_LValue;
6325 }
6326 Expr *E = new (*this)
6327 DeclRefExpr(*this, NTTP, /*RefersToEnclosingVariableOrCapture=*/false,
6328 T, VK, NTTP->getLocation());
6329
6330 if (NTTP->isParameterPack())
6331 E = new (*this) PackExpansionExpr(E, NTTP->getLocation(), std::nullopt);
6332 Arg = TemplateArgument(E, /*IsCanonical=*/false);
6333 } else {
6334 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
6336 /*Qualifier=*/std::nullopt, /*TemplateKeyword=*/false,
6337 TemplateName(TTP));
6338 if (TTP->isParameterPack())
6339 Arg = TemplateArgument(Name, /*NumExpansions=*/std::nullopt);
6340 else
6341 Arg = TemplateArgument(Name);
6342 }
6343
6344 if (Param->isTemplateParameterPack())
6345 Arg =
6346 TemplateArgument::CreatePackCopy(const_cast<ASTContext &>(*this), Arg);
6347
6348 return Arg;
6349}
6350
6352 UnsignedOrNone NumExpansions,
6353 bool ExpectPackInType) const {
6354 assert((!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) &&
6355 "Pack expansions must expand one or more parameter packs");
6356
6357 auto Key = std::make_pair(Pattern, NumExpansions.toInternalRepresentation());
6358
6359 llvm::FoldingSetInsertToken Token;
6360 PackExpansionType *T = PackExpansionTypes.lookup(Key, Token);
6361 if (T)
6362 return QualType(T, 0);
6363
6364 QualType Canon;
6365 if (!Pattern.isCanonical()) {
6366 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions,
6367 /*ExpectPackInType=*/false);
6368
6369 // Find the insert position again, in case we inserted an element into
6370 // PackExpansionTypes and invalidated our insert position.
6371 PackExpansionTypes.lookup(Key, Token);
6372 }
6373
6374 T = new (*this, alignof(PackExpansionType))
6375 PackExpansionType(Pattern, Canon, NumExpansions);
6376 Types.push_back(T);
6377 PackExpansionTypes.insert(T, Token);
6378 return QualType(T, 0);
6379}
6380
6381/// CmpProtocolNames - Comparison predicate for sorting protocols
6382/// alphabetically.
6383static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
6384 ObjCProtocolDecl *const *RHS) {
6385 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
6386}
6387
6389 if (Protocols.empty()) return true;
6390
6391 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
6392 return false;
6393
6394 for (unsigned i = 1; i != Protocols.size(); ++i)
6395 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
6396 Protocols[i]->getCanonicalDecl() != Protocols[i])
6397 return false;
6398 return true;
6399}
6400
6401static void
6403 // Sort protocols, keyed by name.
6404 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
6405
6406 // Canonicalize.
6407 for (ObjCProtocolDecl *&P : Protocols)
6408 P = P->getCanonicalDecl();
6409
6410 // Remove duplicates.
6411 auto ProtocolsEnd = llvm::unique(Protocols);
6412 Protocols.erase(ProtocolsEnd, Protocols.end());
6413}
6414
6416 ObjCProtocolDecl * const *Protocols,
6417 unsigned NumProtocols) const {
6418 return getObjCObjectType(BaseType, {}, ArrayRef(Protocols, NumProtocols),
6419 /*isKindOf=*/false);
6420}
6421
6423 QualType baseType,
6424 ArrayRef<QualType> typeArgs,
6426 bool isKindOf) const {
6427 // If the base type is an interface and there aren't any protocols or
6428 // type arguments to add, then the interface type will do just fine.
6429 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
6430 isa<ObjCInterfaceType>(baseType))
6431 return baseType;
6432
6433 // Look in the folding set for an existing type.
6434 llvm::FoldingSetNodeID ID;
6435 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
6436 llvm::FoldingSetInsertToken Token;
6437 if (ObjCObjectType *QT = ObjCObjectTypes.lookup(ID, Token))
6438 return QualType(QT, 0);
6439
6440 // Determine the type arguments to be used for canonicalization,
6441 // which may be explicitly specified here or written on the base
6442 // type.
6443 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
6444 if (effectiveTypeArgs.empty()) {
6445 if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
6446 effectiveTypeArgs = baseObject->getTypeArgs();
6447 }
6448
6449 // Build the canonical type, which has the canonical base type and a
6450 // sorted-and-uniqued list of protocols and the type arguments
6451 // canonicalized.
6452 QualType canonical;
6453 bool typeArgsAreCanonical = llvm::all_of(
6454 effectiveTypeArgs, [&](QualType type) { return type.isCanonical(); });
6455 bool protocolsSorted = areSortedAndUniqued(protocols);
6456 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
6457 // Determine the canonical type arguments.
6458 ArrayRef<QualType> canonTypeArgs;
6459 SmallVector<QualType, 4> canonTypeArgsVec;
6460 if (!typeArgsAreCanonical) {
6461 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
6462 for (auto typeArg : effectiveTypeArgs)
6463 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
6464 canonTypeArgs = canonTypeArgsVec;
6465 } else {
6466 canonTypeArgs = effectiveTypeArgs;
6467 }
6468
6469 ArrayRef<ObjCProtocolDecl *> canonProtocols;
6470 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
6471 if (!protocolsSorted) {
6472 canonProtocolsVec.append(protocols.begin(), protocols.end());
6473 SortAndUniqueProtocols(canonProtocolsVec);
6474 canonProtocols = canonProtocolsVec;
6475 } else {
6476 canonProtocols = protocols;
6477 }
6478
6479 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
6480 canonProtocols, isKindOf);
6481
6482 // Regenerate Token.
6483 ObjCObjectTypes.lookup(ID, Token);
6484 }
6485
6486 unsigned size = sizeof(ObjCObjectTypeImpl);
6487 size += typeArgs.size() * sizeof(QualType);
6488 size += protocols.size() * sizeof(ObjCProtocolDecl *);
6489 void *mem = Allocate(size, alignof(ObjCObjectTypeImpl));
6490 auto *T =
6491 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
6492 isKindOf);
6493
6494 Types.push_back(T);
6495 ObjCObjectTypes.insert(T, Token);
6496 return QualType(T, 0);
6497}
6498
6499/// Apply Objective-C protocol qualifiers to the given type.
6500/// If this is for the canonical type of a type parameter, we can apply
6501/// protocol qualifiers on the ObjCObjectPointerType.
6504 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
6505 bool allowOnPointerType) const {
6506 hasError = false;
6507
6508 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
6509 return getObjCTypeParamType(objT->getDecl(), protocols);
6510 }
6511
6512 // Apply protocol qualifiers to ObjCObjectPointerType.
6513 if (allowOnPointerType) {
6514 if (const auto *objPtr =
6515 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
6516 const ObjCObjectType *objT = objPtr->getObjectType();
6517 // Merge protocol lists and construct ObjCObjectType.
6519 protocolsVec.append(objT->qual_begin(),
6520 objT->qual_end());
6521 protocolsVec.append(protocols.begin(), protocols.end());
6522 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
6524 objT->getBaseType(),
6525 objT->getTypeArgsAsWritten(),
6526 protocols,
6527 objT->isKindOfTypeAsWritten());
6529 }
6530 }
6531
6532 // Apply protocol qualifiers to ObjCObjectType.
6533 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
6534 // FIXME: Check for protocols to which the class type is already
6535 // known to conform.
6536
6537 return getObjCObjectType(objT->getBaseType(),
6538 objT->getTypeArgsAsWritten(),
6539 protocols,
6540 objT->isKindOfTypeAsWritten());
6541 }
6542
6543 // If the canonical type is ObjCObjectType, ...
6544 if (type->isObjCObjectType()) {
6545 // Silently overwrite any existing protocol qualifiers.
6546 // TODO: determine whether that's the right thing to do.
6547
6548 // FIXME: Check for protocols to which the class type is already
6549 // known to conform.
6550 return getObjCObjectType(type, {}, protocols, false);
6551 }
6552
6553 // id<protocol-list>
6554 if (type->isObjCIdType()) {
6555 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6556 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
6557 objPtr->isKindOfType());
6559 }
6560
6561 // Class<protocol-list>
6562 if (type->isObjCClassType()) {
6563 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6564 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
6565 objPtr->isKindOfType());
6567 }
6568
6569 hasError = true;
6570 return type;
6571}
6572
6575 ArrayRef<ObjCProtocolDecl *> protocols) const {
6576 // We canonicalize to the underlying type.
6577 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
6578 if (!protocols.empty()) {
6579 // Apply the protocol qualifers.
6580 bool hasError;
6582 Canonical, protocols, hasError, true /*allowOnPointerType*/));
6583 assert(!hasError && "Error when apply protocol qualifier to bound type");
6584 }
6585
6586 // Key on the canonical type the node is constructed with, which is what
6587 // Profile() reports; the decl's underlying type can be updated later.
6588 auto Key = std::make_tuple(Decl, Canonical, protocols);
6589 llvm::FoldingSetInsertToken Token;
6590 if (ObjCTypeParamType *TypeParam = ObjCTypeParamTypes.lookup(Key, Token))
6591 return QualType(TypeParam, 0);
6592
6593 unsigned size = sizeof(ObjCTypeParamType);
6594 size += protocols.size() * sizeof(ObjCProtocolDecl *);
6595 void *mem = Allocate(size, alignof(ObjCTypeParamType));
6596 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
6597
6598 Types.push_back(newType);
6599 ObjCTypeParamTypes.insert(newType, Token);
6600 return QualType(newType, 0);
6601}
6602
6604 ObjCTypeParamDecl *New) const {
6605 New->setTypeSourceInfo(getTrivialTypeSourceInfo(Orig->getUnderlyingType()));
6606 // Update TypeForDecl after updating TypeSourceInfo.
6607 auto *NewTypeParamTy = cast<ObjCTypeParamType>(New->TypeForDecl);
6609 protocols.append(NewTypeParamTy->qual_begin(), NewTypeParamTy->qual_end());
6610 QualType UpdatedTy = getObjCTypeParamType(New, protocols);
6611 New->TypeForDecl = UpdatedTy.getTypePtr();
6612}
6613
6614/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
6615/// protocol list adopt all protocols in QT's qualified-id protocol
6616/// list.
6618 ObjCInterfaceDecl *IC) {
6619 if (!QT->isObjCQualifiedIdType())
6620 return false;
6621
6622 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
6623 // If both the right and left sides have qualifiers.
6624 for (auto *Proto : OPT->quals()) {
6625 if (!IC->ClassImplementsProtocol(Proto, false))
6626 return false;
6627 }
6628 return true;
6629 }
6630 return false;
6631}
6632
6633/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
6634/// QT's qualified-id protocol list adopt all protocols in IDecl's list
6635/// of protocols.
6637 ObjCInterfaceDecl *IDecl) {
6638 if (!QT->isObjCQualifiedIdType())
6639 return false;
6640 const auto *OPT = QT->getAs<ObjCObjectPointerType>();
6641 if (!OPT)
6642 return false;
6643 if (!IDecl->hasDefinition())
6644 return false;
6646 CollectInheritedProtocols(IDecl, InheritedProtocols);
6647 if (InheritedProtocols.empty())
6648 return false;
6649 // Check that if every protocol in list of id<plist> conforms to a protocol
6650 // of IDecl's, then bridge casting is ok.
6651 bool Conforms = false;
6652 for (auto *Proto : OPT->quals()) {
6653 Conforms = false;
6654 for (auto *PI : InheritedProtocols) {
6655 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
6656 Conforms = true;
6657 break;
6658 }
6659 }
6660 if (!Conforms)
6661 break;
6662 }
6663 if (Conforms)
6664 return true;
6665
6666 for (auto *PI : InheritedProtocols) {
6667 // If both the right and left sides have qualifiers.
6668 bool Adopts = false;
6669 for (auto *Proto : OPT->quals()) {
6670 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
6671 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
6672 break;
6673 }
6674 if (!Adopts)
6675 return false;
6676 }
6677 return true;
6678}
6679
6680/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
6681/// the given object type.
6683 llvm::FoldingSetInsertToken Token;
6684 if (ObjCObjectPointerType *QT = ObjCObjectPointerTypes.lookup(ObjectT, Token))
6685 return QualType(QT, 0);
6686
6687 // Find the canonical object type.
6688 QualType Canonical;
6689 if (!ObjectT.isCanonical())
6690 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
6691
6692 // No match.
6693 void *Mem =
6695 auto *QType =
6696 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
6697
6698 Types.push_back(QType);
6699 ObjCObjectPointerTypes.insert(QType, Token);
6700 return QualType(QType, 0);
6701}
6702
6703/// getObjCInterfaceType - Return the unique reference to the type for the
6704/// specified ObjC interface decl. The list of protocols is optional.
6706 ObjCInterfaceDecl *PrevDecl) const {
6707 if (Decl->TypeForDecl)
6708 return QualType(Decl->TypeForDecl, 0);
6709
6710 if (PrevDecl) {
6711 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
6712 Decl->TypeForDecl = PrevDecl->TypeForDecl;
6713 return QualType(PrevDecl->TypeForDecl, 0);
6714 }
6715
6716 // Prefer the definition, if there is one.
6717 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
6718 Decl = Def;
6719
6720 void *Mem = Allocate(sizeof(ObjCInterfaceType), alignof(ObjCInterfaceType));
6721 auto *T = new (Mem) ObjCInterfaceType(Decl);
6722 Decl->TypeForDecl = T;
6723 Types.push_back(T);
6724 return QualType(T, 0);
6725}
6726
6727/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
6728/// TypeOfExprType AST's (since expression's are never shared). For example,
6729/// multiple declarations that refer to "typeof(x)" all contain different
6730/// DeclRefExpr's. This doesn't effect the type checker, since it operates
6731/// on canonical type's (which are always unique).
6733 TypeOfExprType *toe;
6734 if (tofExpr->isTypeDependent()) {
6735 llvm::FoldingSetNodeID ID;
6736 DependentTypeOfExprType::Profile(ID, *this, tofExpr,
6737 Kind == TypeOfKind::Unqualified);
6738
6739 llvm::FoldingSetInsertToken Token;
6740 DependentTypeOfExprType *Canon = DependentTypeOfExprTypes.lookup(ID, Token);
6741 if (Canon) {
6742 // We already have a "canonical" version of an identical, dependent
6743 // typeof(expr) type. Use that as our canonical type.
6744 toe = new (*this, alignof(TypeOfExprType)) TypeOfExprType(
6745 *this, tofExpr, Kind, QualType((TypeOfExprType *)Canon, 0));
6746 } else {
6747 // Build a new, canonical typeof(expr) type.
6748 Canon = new (*this, alignof(DependentTypeOfExprType))
6749 DependentTypeOfExprType(*this, tofExpr, Kind);
6750 DependentTypeOfExprTypes.insert(Canon, Token);
6751 toe = Canon;
6752 }
6753 } else {
6754 QualType Canonical = getCanonicalType(tofExpr->getType());
6755 toe = new (*this, alignof(TypeOfExprType))
6756 TypeOfExprType(*this, tofExpr, Kind, Canonical);
6757 }
6758 Types.push_back(toe);
6759 return QualType(toe, 0);
6760}
6761
6762/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
6763/// TypeOfType nodes. The only motivation to unique these nodes would be
6764/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
6765/// an issue. This doesn't affect the type checker, since it operates
6766/// on canonical types (which are always unique).
6768 QualType Canonical = getCanonicalType(tofType);
6769 auto *tot = new (*this, alignof(TypeOfType))
6770 TypeOfType(*this, tofType, Canonical, Kind);
6771 Types.push_back(tot);
6772 return QualType(tot, 0);
6773}
6774
6775/// getReferenceQualifiedType - Given an expr, will return the type for
6776/// that expression, as in [dcl.type.simple]p4 but without taking id-expressions
6777/// and class member access into account.
6779 // C++11 [dcl.type.simple]p4:
6780 // [...]
6781 QualType T = E->getType();
6782 switch (E->getValueKind()) {
6783 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
6784 // type of e;
6785 case VK_XValue:
6786 return getRValueReferenceType(T);
6787 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
6788 // type of e;
6789 case VK_LValue:
6790 return getLValueReferenceType(T);
6791 // - otherwise, decltype(e) is the type of e.
6792 case VK_PRValue:
6793 return T;
6794 }
6795 llvm_unreachable("Unknown value kind");
6796}
6797
6798/// Unlike many "get<Type>" functions, we don't unique DecltypeType
6799/// nodes. This would never be helpful, since each such type has its own
6800/// expression, and would not give a significant memory saving, since there
6801/// is an Expr tree under each such type.
6803 // C++11 [temp.type]p2:
6804 // If an expression e involves a template parameter, decltype(e) denotes a
6805 // unique dependent type. Two such decltype-specifiers refer to the same
6806 // type only if their expressions are equivalent (14.5.6.1).
6807 QualType CanonType;
6808 if (!E->isInstantiationDependent()) {
6809 CanonType = getCanonicalType(UnderlyingType);
6810 } else if (!UnderlyingType.isNull()) {
6811 CanonType = getDecltypeType(E, QualType());
6812 } else {
6813 llvm::FoldingSetNodeID ID;
6814 DependentDecltypeType::Profile(ID, *this, E);
6815
6816 llvm::FoldingSetInsertToken Token;
6817 if (DependentDecltypeType *Canon = DependentDecltypeTypes.lookup(ID, Token))
6818 return QualType(Canon, 0);
6819
6820 // Build a new, canonical decltype(expr) type.
6821 auto *DT =
6822 new (*this, alignof(DependentDecltypeType)) DependentDecltypeType(E);
6823 DependentDecltypeTypes.insert(DT, Token);
6824 Types.push_back(DT);
6825 return QualType(DT, 0);
6826 }
6827 auto *DT = new (*this, alignof(DecltypeType))
6828 DecltypeType(E, UnderlyingType, CanonType);
6829 Types.push_back(DT);
6830 return QualType(DT, 0);
6831}
6832
6834 bool FullySubstituted,
6835 ArrayRef<QualType> Expansions,
6836 UnsignedOrNone Index) const {
6837 QualType Canonical;
6838 if (FullySubstituted && Index) {
6839 Canonical = getCanonicalType(Expansions[*Index]);
6840 } else {
6841 llvm::FoldingSetNodeID ID;
6842 PackIndexingType::Profile(ID, *this, Pattern.getCanonicalType(), IndexExpr,
6843 FullySubstituted, Expansions);
6844 llvm::FoldingSetInsertToken Token;
6845 PackIndexingType *Canon = DependentPackIndexingTypes.lookup(ID, Token);
6846 if (!Canon) {
6847 void *Mem = Allocate(
6848 PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
6850 Canon =
6851 new (Mem) PackIndexingType(QualType(), Pattern.getCanonicalType(),
6852 IndexExpr, FullySubstituted, Expansions);
6853 DependentPackIndexingTypes.insert(Canon, Token);
6854 }
6855 Canonical = QualType(Canon, 0);
6856 }
6857
6858 void *Mem =
6859 Allocate(PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
6861 auto *T = new (Mem) PackIndexingType(Canonical, Pattern, IndexExpr,
6862 FullySubstituted, Expansions);
6863 Types.push_back(T);
6864 return QualType(T, 0);
6865}
6866
6867/// getUnaryTransformationType - We don't unique these, since the memory
6868/// savings are minimal and these are rare.
6871 UnaryTransformType::UTTKind Kind) const {
6872 // Clear UnderlyingType for a dependent base before building the ID: that is
6873 // what the node is constructed with, and what Profile() reports.
6874 if (BaseType->isDependentType()) {
6875 assert(UnderlyingType.isNull() || BaseType == UnderlyingType);
6876 UnderlyingType = QualType();
6877 }
6878
6879 auto Key = std::make_tuple(BaseType, UnderlyingType, Kind);
6880
6881 llvm::FoldingSetInsertToken Token;
6882 if (UnaryTransformType *UT = UnaryTransformTypes.lookup(Key, Token))
6883 return QualType(UT, 0);
6884
6885 QualType CanonType;
6886 if (!BaseType->isDependentType()) {
6887 CanonType = UnderlyingType.getCanonicalType();
6888 } else {
6889 if (QualType CanonBase = BaseType.getCanonicalType();
6890 BaseType != CanonBase) {
6891 CanonType = getUnaryTransformType(CanonBase, QualType(), Kind);
6892 assert(CanonType.isCanonical());
6893 }
6894 }
6895
6896 auto *UT = new (*this, alignof(UnaryTransformType))
6897 UnaryTransformType(BaseType, UnderlyingType, Kind, CanonType);
6898 UnaryTransformTypes.insert(UT, Token);
6899 Types.push_back(UT);
6900 return QualType(UT, 0);
6901}
6902
6903/// getAutoType - Return the uniqued reference to the 'auto' type which has been
6904/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
6905/// canonical deduced-but-dependent 'auto' type.
6909 TemplateName TypeConstraintConcept,
6910 ArrayRef<TemplateArgument> TypeConstraintArgs) const {
6912 TypeConstraintConcept.isNull()) {
6913 assert(DeducedAsType.isNull() && "");
6914 assert(TypeConstraintArgs.empty() && "");
6915 return getAutoDeductType();
6916 }
6917
6918 // Look in the folding set for an existing type.
6919 llvm::FoldingSetNodeID ID;
6920 AutoType::Profile(ID, *this, DK, DeducedAsType, Keyword,
6921 TypeConstraintConcept, TypeConstraintArgs);
6922 if (auto const AT_iter = AutoTypes.find_as(ID); AT_iter != AutoTypes.end())
6923 return QualType(AT_iter->getSecond(), 0);
6924
6925 if (DK == DeducedKind::Deduced) {
6926 assert(!DeducedAsType.isNull() && "deduced type must be provided");
6927 } else {
6928 assert(DeducedAsType.isNull() && "deduced type must not be provided");
6929 if (!TypeConstraintConcept.isNull()) {
6930 bool AnyNonCanonArgs = false;
6931 TemplateName CanonicalConcept =
6932 getCanonicalTemplateName(TypeConstraintConcept);
6933 auto CanonicalConceptArgs = ::getCanonicalTemplateArguments(
6934 *this, TypeConstraintArgs, AnyNonCanonArgs);
6935 if (TypeConstraintConcept != CanonicalConcept || AnyNonCanonArgs)
6936 DeducedAsType = getAutoType(DK, QualType(), Keyword, CanonicalConcept,
6937 CanonicalConceptArgs);
6938 }
6939 }
6940
6941 void *Mem = Allocate(sizeof(AutoType) +
6942 sizeof(TemplateArgument) * TypeConstraintArgs.size(),
6943 alignof(AutoType));
6944 auto *AT = new (Mem) AutoType(DK, DeducedAsType, Keyword,
6945 TypeConstraintConcept, TypeConstraintArgs);
6946#ifndef NDEBUG
6947 llvm::FoldingSetNodeID InsertedID;
6948 AT->Profile(InsertedID, *this);
6949 assert(InsertedID == ID && "ID does not match");
6950#endif
6951 Types.push_back(AT);
6952 AutoTypes.try_emplace(ID.Intern(BumpAlloc), AT);
6953 return QualType(AT, 0);
6954}
6955
6957 QualType CanonT = T.getNonPackExpansionType().getCanonicalType();
6958
6959 // Remove a type-constraint from a top-level auto or decltype(auto).
6960 if (auto *AT = CanonT->getAs<AutoType>()) {
6961 if (!AT->isConstrained())
6962 return T;
6963 return getQualifiedType(
6964 getAutoType(AT->getDeducedKind(), QualType(), AT->getKeyword()),
6965 T.getQualifiers());
6966 }
6967
6968 // FIXME: We only support constrained auto at the top level in the type of a
6969 // non-type template parameter at the moment. Once we lift that restriction,
6970 // we'll need to recursively build types containing auto here.
6971 assert(!CanonT->getContainedAutoType() ||
6972 !CanonT->getContainedAutoType()->isConstrained());
6973 return T;
6974}
6975
6976/// Return the uniqued reference to the deduced template specialization type
6977/// which has been deduced to the given type, or to the canonical undeduced
6978/// such type, or the canonical deduced-but-dependent such type.
6981 TemplateName Template) const {
6982 // Look in the folding set for an existing type.
6983 llvm::FoldingSetInsertToken Token;
6984 llvm::FoldingSetNodeID ID;
6985 DeducedTemplateSpecializationType::Profile(ID, DK, DeducedAsType, Keyword,
6986 Template);
6987 if (DeducedTemplateSpecializationType *DTST =
6988 DeducedTemplateSpecializationTypes.lookup(ID, Token))
6989 return QualType(DTST, 0);
6990
6991 if (DK == DeducedKind::Deduced) {
6992 assert(!DeducedAsType.isNull() && "deduced type must be provided");
6993 } else {
6994 assert(DeducedAsType.isNull() && "deduced type must not be provided");
6995 TemplateName CanonTemplateName = getCanonicalTemplateName(Template);
6996 // FIXME: Can this be formed from a DependentTemplateName, such that the
6997 // keyword should be part of the canonical type?
6999 Template != CanonTemplateName) {
7001 DK, QualType(), ElaboratedTypeKeyword::None, CanonTemplateName);
7002 // Find the insertion position again.
7003 [[maybe_unused]] DeducedTemplateSpecializationType *DTST =
7004 DeducedTemplateSpecializationTypes.lookup(ID, Token);
7005 assert(!DTST && "broken canonicalization");
7006 }
7007 }
7008
7009 auto *DTST = new (*this, alignof(DeducedTemplateSpecializationType))
7010 DeducedTemplateSpecializationType(DK, DeducedAsType, Keyword, Template);
7011
7012#ifndef NDEBUG
7013 llvm::FoldingSetNodeID TempID;
7014 DTST->Profile(TempID);
7015 assert(ID == TempID && "ID does not match");
7016#endif
7017 Types.push_back(DTST);
7018 DeducedTemplateSpecializationTypes.insert(DTST, Token);
7019 return QualType(DTST, 0);
7020}
7021
7022/// getAtomicType - Return the uniqued reference to the atomic type for
7023/// the given value type.
7025 // Unique pointers, to guarantee there is only one pointer of a particular
7026 // structure.
7027 llvm::FoldingSetInsertToken Token;
7028 if (AtomicType *AT = AtomicTypes.lookup(T, Token))
7029 return QualType(AT, 0);
7030
7031 // If the atomic value type isn't canonical, this won't be a canonical type
7032 // either, so fill in the canonical type field.
7033 QualType Canonical;
7034 if (!T.isCanonical()) {
7035 Canonical = getAtomicType(getCanonicalType(T));
7036
7037 assert(!AtomicTypes.lookup(T, Token) && "Shouldn't be in the map!");
7038 }
7039 auto *New = new (*this, alignof(AtomicType)) AtomicType(T, Canonical);
7040 Types.push_back(New);
7041 AtomicTypes.insert(New, Token);
7042 return QualType(New, 0);
7043}
7044
7045/// getAutoDeductType - Get type pattern for deducing against 'auto'.
7047 if (AutoDeductTy.isNull())
7049 new (*this, alignof(AutoType))
7051 /*TypeConstraintConcept=*/TemplateName(),
7052 /*TypeConstraintArgs=*/{}),
7053 0);
7054 return AutoDeductTy;
7055}
7056
7057/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
7059 if (AutoRRefDeductTy.isNull())
7061 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
7062 return AutoRRefDeductTy;
7063}
7064
7065/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
7066/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
7067/// needs to agree with the definition in <stddef.h>.
7071
7073 return getFromTargetType(Target->getSizeType());
7074}
7075
7076/// Return the unique signed counterpart of the integer type
7077/// corresponding to size_t.
7081
7082/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
7083/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
7087
7088/// Return the unique unsigned counterpart of "ptrdiff_t"
7089/// integer type. The standard (C11 7.21.6.1p7) refers to this type
7090/// in the definition of %tu format specifier.
7092 return getFromTargetType(Target->getUnsignedPtrDiffType(LangAS::Default));
7093}
7094
7095/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
7097 return getFromTargetType(Target->getIntMaxType());
7098}
7099
7100/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
7102 return getFromTargetType(Target->getUIntMaxType());
7103}
7104
7105/// getSignedWCharType - Return the type of "signed wchar_t".
7106/// Used when in C++, as a GCC extension.
7108 // FIXME: derive from "Target" ?
7109 return WCharTy;
7110}
7111
7112/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
7113/// Used when in C++, as a GCC extension.
7115 // FIXME: derive from "Target" ?
7116 return UnsignedIntTy;
7117}
7118
7120 return getFromTargetType(Target->getIntPtrType());
7121}
7122
7126
7127/// Return the unique type for "pid_t" defined in
7128/// <sys/types.h>. We need this to compute the correct type for vfork().
7130 return getFromTargetType(Target->getProcessIDType());
7131}
7132
7133//===----------------------------------------------------------------------===//
7134// Type Operators
7135//===----------------------------------------------------------------------===//
7136
7138 // Push qualifiers into arrays, and then discard any remaining
7139 // qualifiers.
7140 T = getCanonicalType(T);
7142 const Type *Ty = T.getTypePtr();
7146 } else if (isa<ArrayType>(Ty)) {
7148 } else if (isa<FunctionType>(Ty)) {
7149 Result = getPointerType(QualType(Ty, 0));
7150 } else {
7151 Result = QualType(Ty, 0);
7152 }
7153
7155}
7156
7158 Qualifiers &quals) const {
7159 SplitQualType splitType = type.getSplitUnqualifiedType();
7160
7161 // FIXME: getSplitUnqualifiedType() actually walks all the way to
7162 // the unqualified desugared type and then drops it on the floor.
7163 // We then have to strip that sugar back off with
7164 // getUnqualifiedDesugaredType(), which is silly.
7165 const auto *AT =
7166 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
7167
7168 // If we don't have an array, just use the results in splitType.
7169 if (!AT) {
7170 quals = splitType.Quals;
7171 return QualType(splitType.Ty, 0);
7172 }
7173
7174 // Otherwise, recurse on the array's element type.
7175 QualType elementType = AT->getElementType();
7176 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
7177
7178 // If that didn't change the element type, AT has no qualifiers, so we
7179 // can just use the results in splitType.
7180 if (elementType == unqualElementType) {
7181 assert(quals.empty()); // from the recursive call
7182 quals = splitType.Quals;
7183 return QualType(splitType.Ty, 0);
7184 }
7185
7186 // Otherwise, add in the qualifiers from the outermost type, then
7187 // build the type back up.
7188 quals.addConsistentQualifiers(splitType.Quals);
7189
7190 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
7191 return getConstantArrayType(unqualElementType, CAT->getSize(),
7192 CAT->getSizeExpr(), CAT->getSizeModifier(), 0);
7193 }
7194
7195 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
7196 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
7197 }
7198
7199 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
7200 return getVariableArrayType(unqualElementType, VAT->getSizeExpr(),
7201 VAT->getSizeModifier(),
7202 VAT->getIndexTypeCVRQualifiers());
7203 }
7204
7205 const auto *DSAT = cast<DependentSizedArrayType>(AT);
7206 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
7207 DSAT->getSizeModifier(), 0);
7208}
7209
7210/// Attempt to unwrap two types that may both be array types with the same bound
7211/// (or both be array types of unknown bound) for the purpose of comparing the
7212/// cv-decomposition of two types per C++ [conv.qual].
7213///
7214/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
7215/// C++20 [conv.qual], if permitted by the current language mode.
7217 bool AllowPiMismatch) const {
7218 while (true) {
7219 auto *AT1 = getAsArrayType(T1);
7220 if (!AT1)
7221 return;
7222
7223 auto *AT2 = getAsArrayType(T2);
7224 if (!AT2)
7225 return;
7226
7227 // If we don't have two array types with the same constant bound nor two
7228 // incomplete array types, we've unwrapped everything we can.
7229 // C++20 also permits one type to be a constant array type and the other
7230 // to be an incomplete array type.
7231 // FIXME: Consider also unwrapping array of unknown bound and VLA.
7232 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
7233 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
7234 if (!((CAT2 && CAT1->getSize() == CAT2->getSize()) ||
7235 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
7237 return;
7238 } else if (isa<IncompleteArrayType>(AT1)) {
7239 if (!(isa<IncompleteArrayType>(AT2) ||
7240 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
7242 return;
7243 } else {
7244 return;
7245 }
7246
7247 T1 = AT1->getElementType();
7248 T2 = AT2->getElementType();
7249 }
7250}
7251
7252/// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
7253///
7254/// If T1 and T2 are both pointer types of the same kind, or both array types
7255/// with the same bound, unwraps layers from T1 and T2 until a pointer type is
7256/// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
7257///
7258/// This function will typically be called in a loop that successively
7259/// "unwraps" pointer and pointer-to-member types to compare them at each
7260/// level.
7261///
7262/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
7263/// C++20 [conv.qual], if permitted by the current language mode.
7264///
7265/// \return \c true if a pointer type was unwrapped, \c false if we reached a
7266/// pair of types that can't be unwrapped further.
7268 bool AllowPiMismatch) const {
7269 UnwrapSimilarArrayTypes(T1, T2, AllowPiMismatch);
7270
7271 const auto *T1PtrType = T1->getAs<PointerType>();
7272 const auto *T2PtrType = T2->getAs<PointerType>();
7273 if (T1PtrType && T2PtrType) {
7274 T1 = T1PtrType->getPointeeType();
7275 T2 = T2PtrType->getPointeeType();
7276 return true;
7277 }
7278
7279 if (const auto *T1MPType = T1->getAsCanonical<MemberPointerType>(),
7280 *T2MPType = T2->getAsCanonical<MemberPointerType>();
7281 T1MPType && T2MPType) {
7282 // Compare the qualifiers of the canonical type, as the non-canonical type
7283 // may have qualifiers pointing to a base or derived class.
7284 if (T1MPType->getQualifier() != T2MPType->getQualifier())
7285 return false;
7286 // Get the pointee types of the non-canonical type, in order to preserve
7287 // their sugar.
7288 T1 = T1->getAs<MemberPointerType>()->getPointeeType();
7289 T2 = T2->getAs<MemberPointerType>()->getPointeeType();
7290 return true;
7291 }
7292
7293 if (getLangOpts().ObjC) {
7294 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
7295 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
7296 if (T1OPType && T2OPType) {
7297 T1 = T1OPType->getPointeeType();
7298 T2 = T2OPType->getPointeeType();
7299 return true;
7300 }
7301 }
7302
7303 // FIXME: Block pointers, too?
7304
7305 return false;
7306}
7307
7309 while (true) {
7310 Qualifiers Quals;
7311 T1 = getUnqualifiedArrayType(T1, Quals);
7312 T2 = getUnqualifiedArrayType(T2, Quals);
7313 if (hasSameType(T1, T2))
7314 return true;
7315 if (!UnwrapSimilarTypes(T1, T2))
7316 return false;
7317 }
7318}
7319
7321 while (true) {
7322 Qualifiers Quals1, Quals2;
7323 T1 = getUnqualifiedArrayType(T1, Quals1);
7324 T2 = getUnqualifiedArrayType(T2, Quals2);
7325
7326 Quals1.removeCVRQualifiers();
7327 Quals2.removeCVRQualifiers();
7328 if (Quals1 != Quals2)
7329 return false;
7330
7331 if (hasSameType(T1, T2))
7332 return true;
7333
7334 if (!UnwrapSimilarTypes(T1, T2, /*AllowPiMismatch*/ false))
7335 return false;
7336 }
7337}
7338
7341 SourceLocation NameLoc) const {
7342 switch (Name.getKind()) {
7345 // DNInfo work in progress: CHECKME: what about DNLoc?
7347 NameLoc);
7348
7351 // DNInfo work in progress: CHECKME: what about DNLoc?
7352 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
7353 }
7354
7357 return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
7358 }
7359
7363 DeclarationName DName;
7364 if (const IdentifierInfo *II = TN.getIdentifier()) {
7365 DName = DeclarationNames.getIdentifier(II);
7366 return DeclarationNameInfo(DName, NameLoc);
7367 } else {
7368 DName = DeclarationNames.getCXXOperatorName(TN.getOperator());
7369 // DNInfo work in progress: FIXME: source locations?
7370 DeclarationNameLoc DNLoc =
7372 return DeclarationNameInfo(DName, NameLoc, DNLoc);
7373 }
7374 }
7375
7379 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
7380 NameLoc);
7381 }
7382
7387 NameLoc);
7388 }
7391 NameLoc);
7394 return getNameForTemplate(DTS->getUnderlying(), NameLoc);
7395 }
7398 return getNameForTemplate(PI->getPattern(), NameLoc);
7399 }
7400 }
7401
7402 llvm_unreachable("bad template name kind!");
7403}
7404
7405const TemplateArgument *
7407 auto handleParam = [](auto *TP) -> const TemplateArgument * {
7408 if (!TP->hasDefaultArgument())
7409 return nullptr;
7410 return &TP->getDefaultArgument().getArgument();
7411 };
7412 switch (P->getKind()) {
7413 case NamedDecl::TemplateTypeParm:
7414 return handleParam(cast<TemplateTypeParmDecl>(P));
7415 case NamedDecl::NonTypeTemplateParm:
7416 return handleParam(cast<NonTypeTemplateParmDecl>(P));
7417 case NamedDecl::TemplateTemplateParm:
7418 return handleParam(cast<TemplateTemplateParmDecl>(P));
7419 default:
7420 llvm_unreachable("Unexpected template parameter kind");
7421 }
7422}
7423
7425 bool IgnoreDeduced) const {
7426 while (std::optional<TemplateName> UnderlyingOrNone =
7427 Name.desugar(IgnoreDeduced))
7428 Name = *UnderlyingOrNone;
7429
7430 switch (Name.getKind()) {
7433 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template))
7435
7436 // The canonical template name is the canonical template declaration.
7437 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
7438 }
7439
7441 // An assumed template is just a name, so it is already canonical.
7442 return Name;
7443
7445 llvm_unreachable("cannot canonicalize overloaded template");
7446
7449 assert(DTN && "Non-dependent template names must refer to template decls.");
7450 NestedNameSpecifier Qualifier = DTN->getQualifier();
7451 NestedNameSpecifier CanonQualifier = Qualifier.getCanonical();
7452 if (Qualifier != CanonQualifier || !DTN->hasTemplateKeyword())
7453 return getDependentTemplateName({CanonQualifier, DTN->getName(),
7454 /*HasTemplateKeyword=*/true});
7455 return Name;
7456 }
7457
7461 TemplateArgument canonArgPack =
7464 canonArgPack, subst->getAssociatedDecl()->getCanonicalDecl(),
7465 subst->getIndex(), subst->getFinal());
7466 }
7467
7470 SmallVector<TemplateName, 4> CanonExpansions;
7471 for (TemplateName T : PI->getExpansions())
7472 CanonExpansions.push_back(getCanonicalTemplateName(T, IgnoreDeduced));
7474 getCanonicalTemplateName(PI->getPattern(), IgnoreDeduced),
7475 PI->getIndexExpr(), PI->isFullySubstituted(), CanonExpansions);
7476 }
7478 assert(IgnoreDeduced == false);
7480 DefaultArguments DefArgs = DTS->getDefaultArguments();
7481 TemplateName Underlying = DTS->getUnderlying();
7482
7483 TemplateName CanonUnderlying =
7484 getCanonicalTemplateName(Underlying, /*IgnoreDeduced=*/true);
7485 bool NonCanonical = CanonUnderlying != Underlying;
7486 auto CanonArgs =
7487 getCanonicalTemplateArguments(*this, DefArgs.Args, NonCanonical);
7488
7489 ArrayRef<NamedDecl *> Params =
7490 CanonUnderlying.getAsTemplateDecl()->getTemplateParameters()->asArray();
7491 assert(CanonArgs.size() <= Params.size());
7492 // A deduced template name which deduces the same default arguments already
7493 // declared in the underlying template is the same template as the
7494 // underlying template. We need need to note any arguments which differ from
7495 // the corresponding declaration. If any argument differs, we must build a
7496 // deduced template name.
7497 for (int I = CanonArgs.size() - 1; I >= 0; --I) {
7499 if (!A)
7500 break;
7501 auto CanonParamDefArg = getCanonicalTemplateArgument(*A);
7502 TemplateArgument &CanonDefArg = CanonArgs[I];
7503 if (CanonDefArg.structurallyEquals(CanonParamDefArg))
7504 continue;
7505 // Keep popping from the back any deault arguments which are the same.
7506 if (I == int(CanonArgs.size() - 1))
7507 CanonArgs.pop_back();
7508 NonCanonical = true;
7509 }
7510 return NonCanonical ? getDeducedTemplateName(
7511 CanonUnderlying,
7512 /*DefaultArgs=*/{DefArgs.StartPos, CanonArgs})
7513 : Name;
7514 }
7518 llvm_unreachable("always sugar node");
7519 }
7520
7521 llvm_unreachable("bad template name!");
7522}
7523
7525 const TemplateName &Y,
7526 bool IgnoreDeduced) const {
7527 return getCanonicalTemplateName(X, IgnoreDeduced) ==
7528 getCanonicalTemplateName(Y, IgnoreDeduced);
7529}
7530
7532 const AssociatedConstraint &ACX, const AssociatedConstraint &ACY) const {
7533 if (ACX.ArgPackSubstIndex != ACY.ArgPackSubstIndex)
7534 return false;
7536 return false;
7537 return true;
7538}
7539
7540bool ASTContext::isSameConstraintExpr(const Expr *XCE, const Expr *YCE) const {
7541 if (!XCE != !YCE)
7542 return false;
7543
7544 if (!XCE)
7545 return true;
7546
7547 llvm::FoldingSetNodeID XCEID, YCEID;
7548 XCE->Profile(XCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7549 YCE->Profile(YCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7550 return XCEID == YCEID;
7551}
7552
7554 const TypeConstraint *YTC) const {
7555 if (!XTC != !YTC)
7556 return false;
7557
7558 if (!XTC)
7559 return true;
7560
7563 if (!NCX || !NCY || !isSameEntity(NCX, NCY))
7564 return false;
7567 return false;
7569 if (XTC->getConceptReference()
7571 ->NumTemplateArgs !=
7573 return false;
7574
7575 // Compare slowly by profiling.
7576 //
7577 // We couldn't compare the profiling result for the template
7578 // args here. Consider the following example in different modules:
7579 //
7580 // template <__integer_like _Tp, C<_Tp> Sentinel>
7581 // constexpr _Tp operator()(_Tp &&__t, Sentinel &&last) const {
7582 // return __t;
7583 // }
7584 //
7585 // When we compare the profiling result for `C<_Tp>` in different
7586 // modules, it will compare the type of `_Tp` in different modules.
7587 // However, the type of `_Tp` in different modules refer to different
7588 // types here naturally. So we couldn't compare the profiling result
7589 // for the template args directly.
7592}
7593
7595 const NamedDecl *Y) const {
7596 if (X->getKind() != Y->getKind())
7597 return false;
7598
7599 if (auto *TX = dyn_cast<TemplateTypeParmDecl>(X)) {
7600 auto *TY = cast<TemplateTypeParmDecl>(Y);
7601 if (TX->isParameterPack() != TY->isParameterPack())
7602 return false;
7603 if (TX->hasTypeConstraint() != TY->hasTypeConstraint())
7604 return false;
7605 return isSameTypeConstraint(TX->getTypeConstraint(),
7606 TY->getTypeConstraint());
7607 }
7608
7609 if (auto *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
7610 auto *TY = cast<NonTypeTemplateParmDecl>(Y);
7611 return TX->isParameterPack() == TY->isParameterPack() &&
7612 TX->getASTContext().hasSameType(TX->getType(), TY->getType()) &&
7613 isSameConstraintExpr(TX->getPlaceholderTypeConstraint(),
7614 TY->getPlaceholderTypeConstraint());
7615 }
7616
7618 auto *TY = cast<TemplateTemplateParmDecl>(Y);
7619 return TX->isParameterPack() == TY->isParameterPack() &&
7620 isSameTemplateParameterList(TX->getTemplateParameters(),
7621 TY->getTemplateParameters());
7622}
7623
7625 const TemplateParameterList *X, const TemplateParameterList *Y) const {
7626 if (X->size() != Y->size())
7627 return false;
7628
7629 for (unsigned I = 0, N = X->size(); I != N; ++I)
7630 if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I)))
7631 return false;
7632
7633 return isSameConstraintExpr(X->getRequiresClause(), Y->getRequiresClause());
7634}
7635
7637 const NamedDecl *Y) const {
7638 // If the type parameter isn't the same already, we don't need to check the
7639 // default argument further.
7640 if (!isSameTemplateParameter(X, Y))
7641 return false;
7642
7643 if (auto *TTPX = dyn_cast<TemplateTypeParmDecl>(X)) {
7644 auto *TTPY = cast<TemplateTypeParmDecl>(Y);
7645 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7646 return false;
7647
7648 return hasSameType(TTPX->getDefaultArgument().getArgument().getAsType(),
7649 TTPY->getDefaultArgument().getArgument().getAsType());
7650 }
7651
7652 if (auto *NTTPX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
7653 auto *NTTPY = cast<NonTypeTemplateParmDecl>(Y);
7654 if (!NTTPX->hasDefaultArgument() || !NTTPY->hasDefaultArgument())
7655 return false;
7656
7657 Expr *DefaultArgumentX =
7658 NTTPX->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7659 Expr *DefaultArgumentY =
7660 NTTPY->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7661 llvm::FoldingSetNodeID XID, YID;
7662 DefaultArgumentX->Profile(XID, *this, /*Canonical=*/true);
7663 DefaultArgumentY->Profile(YID, *this, /*Canonical=*/true);
7664 return XID == YID;
7665 }
7666
7667 auto *TTPX = cast<TemplateTemplateParmDecl>(X);
7668 auto *TTPY = cast<TemplateTemplateParmDecl>(Y);
7669
7670 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7671 return false;
7672
7673 const TemplateArgument &TAX = TTPX->getDefaultArgument().getArgument();
7674 const TemplateArgument &TAY = TTPY->getDefaultArgument().getArgument();
7675 return hasSameTemplateName(TAX.getAsTemplate(), TAY.getAsTemplate());
7676}
7677
7679 const NestedNameSpecifier Y) {
7680 if (X == Y)
7681 return true;
7682 if (!X || !Y)
7683 return false;
7684
7685 auto Kind = X.getKind();
7686 if (Kind != Y.getKind())
7687 return false;
7688
7689 // FIXME: For namespaces and types, we're permitted to check that the entity
7690 // is named via the same tokens. We should probably do so.
7691 switch (Kind) {
7693 auto [NamespaceX, PrefixX] = X.getAsNamespaceAndPrefix();
7694 auto [NamespaceY, PrefixY] = Y.getAsNamespaceAndPrefix();
7695 if (!declaresSameEntity(NamespaceX->getNamespace(),
7696 NamespaceY->getNamespace()))
7697 return false;
7698 return isSameQualifier(PrefixX, PrefixY);
7699 }
7701 const auto *TX = X.getAsType(), *TY = Y.getAsType();
7702 if (TX->getCanonicalTypeInternal() != TY->getCanonicalTypeInternal())
7703 return false;
7704 return isSameQualifier(TX->getPrefix(), TY->getPrefix());
7705 }
7709 return true;
7710 }
7711 llvm_unreachable("unhandled qualifier kind");
7712}
7713
7714static bool hasSameCudaAttrs(const FunctionDecl *A, const FunctionDecl *B) {
7715 if (!A->getASTContext().getLangOpts().CUDA)
7716 return true; // Target attributes are overloadable in CUDA compilation only.
7717 if (A->hasAttr<CUDADeviceAttr>() != B->hasAttr<CUDADeviceAttr>())
7718 return false;
7719 if (A->hasAttr<CUDADeviceAttr>() && B->hasAttr<CUDADeviceAttr>())
7720 return A->hasAttr<CUDAHostAttr>() == B->hasAttr<CUDAHostAttr>();
7721 return true; // unattributed and __host__ functions are the same.
7722}
7723
7724/// Determine whether the attributes we can overload on are identical for A and
7725/// B. Will ignore any overloadable attrs represented in the type of A and B.
7727 const FunctionDecl *B) {
7728 // Note that pass_object_size attributes are represented in the function's
7729 // ExtParameterInfo, so we don't need to check them here.
7730
7731 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
7732 auto AEnableIfAttrs = A->specific_attrs<EnableIfAttr>();
7733 auto BEnableIfAttrs = B->specific_attrs<EnableIfAttr>();
7734
7735 for (auto Pair : zip_longest(AEnableIfAttrs, BEnableIfAttrs)) {
7736 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
7737 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
7738
7739 // Return false if the number of enable_if attributes is different.
7740 if (!Cand1A || !Cand2A)
7741 return false;
7742
7743 Cand1ID.clear();
7744 Cand2ID.clear();
7745
7746 (*Cand1A)->getCond()->Profile(Cand1ID, A->getASTContext(), true);
7747 (*Cand2A)->getCond()->Profile(Cand2ID, B->getASTContext(), true);
7748
7749 // Return false if any of the enable_if expressions of A and B are
7750 // different.
7751 if (Cand1ID != Cand2ID)
7752 return false;
7753 }
7754 return hasSameCudaAttrs(A, B);
7755}
7756
7757bool ASTContext::isSameEntity(const NamedDecl *X, const NamedDecl *Y) const {
7758 // Caution: this function is called by the AST reader during deserialization,
7759 // so it cannot rely on AST invariants being met. Non-trivial accessors
7760 // should be avoided, along with any traversal of redeclaration chains.
7761
7762 if (X == Y)
7763 return true;
7764
7765 if (X->getDeclName() != Y->getDeclName())
7766 return false;
7767
7768 // Must be in the same context.
7769 //
7770 // Note that we can't use DeclContext::Equals here, because the DeclContexts
7771 // could be two different declarations of the same function. (We will fix the
7772 // semantic DC to refer to the primary definition after merging.)
7773 if (!declaresSameEntity(cast<Decl>(X->getDeclContext()->getRedeclContext()),
7775 return false;
7776
7777 // If either X or Y are local to the owning module, they are only possible to
7778 // be the same entity if they are in the same module, or if they are members
7779 // of a lambda closure type. Closure types are merged by identity, and a class
7780 // definition determines its members, so the members of a merged closure type
7781 // are the same entity even if they are module-local to different modules.
7782 // Two distinct closure types are still not merged, so their members are never
7783 // compared.
7784 if (X->isModuleLocal() || Y->isModuleLocal()) {
7785 auto *RD = dyn_cast<CXXRecordDecl>(X->getDeclContext());
7786 if (!isInSameModule(X->getOwningModule(), Y->getOwningModule()) &&
7787 !(RD && RD->isLambda()))
7788 return false;
7789 }
7790
7791 // Two typedefs refer to the same entity if they have the same underlying
7792 // type.
7793 if (const auto *TypedefX = dyn_cast<TypedefNameDecl>(X))
7794 if (const auto *TypedefY = dyn_cast<TypedefNameDecl>(Y))
7795 return hasSameType(TypedefX->getUnderlyingType(),
7796 TypedefY->getUnderlyingType());
7797
7798 // Must have the same kind.
7799 if (X->getKind() != Y->getKind())
7800 return false;
7801
7802 // Objective-C classes and protocols with the same name always match.
7804 return true;
7805
7807 // No need to handle these here: we merge them when adding them to the
7808 // template.
7809 return false;
7810 }
7811
7812 // Compatible tags match.
7813 if (const auto *TagX = dyn_cast<TagDecl>(X)) {
7814 const auto *TagY = cast<TagDecl>(Y);
7815 return (TagX->getTagKind() == TagY->getTagKind()) ||
7816 ((TagX->getTagKind() == TagTypeKind::Struct ||
7817 TagX->getTagKind() == TagTypeKind::Class ||
7818 TagX->getTagKind() == TagTypeKind::Interface) &&
7819 (TagY->getTagKind() == TagTypeKind::Struct ||
7820 TagY->getTagKind() == TagTypeKind::Class ||
7821 TagY->getTagKind() == TagTypeKind::Interface));
7822 }
7823
7824 // Functions with the same type and linkage match.
7825 // FIXME: This needs to cope with merging of prototyped/non-prototyped
7826 // functions, etc.
7827 if (const auto *FuncX = dyn_cast<FunctionDecl>(X)) {
7828 const auto *FuncY = cast<FunctionDecl>(Y);
7829 if (const auto *CtorX = dyn_cast<CXXConstructorDecl>(X)) {
7830 const auto *CtorY = cast<CXXConstructorDecl>(Y);
7831 if (CtorX->getInheritedConstructor() &&
7832 !isSameEntity(CtorX->getInheritedConstructor().getConstructor(),
7833 CtorY->getInheritedConstructor().getConstructor()))
7834 return false;
7835 }
7836
7837 if (FuncX->isMultiVersion() != FuncY->isMultiVersion())
7838 return false;
7839
7840 // Multiversioned functions with different feature strings are represented
7841 // as separate declarations.
7842 if (FuncX->isMultiVersion()) {
7843 const auto *TAX = FuncX->getAttr<TargetAttr>();
7844 const auto *TAY = FuncY->getAttr<TargetAttr>();
7845 assert(TAX && TAY && "Multiversion Function without target attribute");
7846
7847 if (TAX->getFeaturesStr() != TAY->getFeaturesStr())
7848 return false;
7849 }
7850
7851 // Per C++20 [temp.over.link]/4, friends in different classes are sometimes
7852 // not the same entity if they are constrained.
7853 if ((FuncX->isMemberLikeConstrainedFriend() ||
7854 FuncY->isMemberLikeConstrainedFriend()) &&
7855 !FuncX->getLexicalDeclContext()->Equals(
7856 FuncY->getLexicalDeclContext())) {
7857 return false;
7858 }
7859
7860 if (!isSameAssociatedConstraint(FuncX->getTrailingRequiresClause(),
7861 FuncY->getTrailingRequiresClause()))
7862 return false;
7863
7864 auto GetTypeAsWritten = [](const FunctionDecl *FD) {
7865 // Map to the first declaration that we've already merged into this one.
7866 // The TSI of redeclarations might not match (due to calling conventions
7867 // being inherited onto the type but not the TSI), but the TSI type of
7868 // the first declaration of the function should match across modules.
7869 FD = FD->getCanonicalDecl();
7870 return FD->getTypeSourceInfo() ? FD->getTypeSourceInfo()->getType()
7871 : FD->getType();
7872 };
7873 QualType XT = GetTypeAsWritten(FuncX), YT = GetTypeAsWritten(FuncY);
7874 if (!hasSameType(XT, YT)) {
7875 // We can get functions with different types on the redecl chain in C++17
7876 // if they have differing exception specifications and at least one of
7877 // the excpetion specs is unresolved.
7878 auto *XFPT = XT->getAs<FunctionProtoType>();
7879 auto *YFPT = YT->getAs<FunctionProtoType>();
7880 if (getLangOpts().CPlusPlus17 && XFPT && YFPT &&
7881 (isUnresolvedExceptionSpec(XFPT->getExceptionSpecType()) ||
7884 return true;
7885 return false;
7886 }
7887
7888 return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() &&
7889 hasSameOverloadableAttrs(FuncX, FuncY);
7890 }
7891
7892 // Variables with the same type and linkage match.
7893 if (const auto *VarX = dyn_cast<VarDecl>(X)) {
7894 const auto *VarY = cast<VarDecl>(Y);
7895 if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) {
7896 // During deserialization, we might compare variables before we load
7897 // their types. Assume the types will end up being the same.
7898 if (VarX->getType().isNull() || VarY->getType().isNull())
7899 return true;
7900
7901 if (hasSameType(VarX->getType(), VarY->getType()))
7902 return true;
7903
7904 // We can get decls with different types on the redecl chain. Eg.
7905 // template <typename T> struct S { static T Var[]; }; // #1
7906 // template <typename T> T S<T>::Var[sizeof(T)]; // #2
7907 // Only? happens when completing an incomplete array type. In this case
7908 // when comparing #1 and #2 we should go through their element type.
7909 const ArrayType *VarXTy = getAsArrayType(VarX->getType());
7910 const ArrayType *VarYTy = getAsArrayType(VarY->getType());
7911 if (!VarXTy || !VarYTy)
7912 return false;
7913 if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType())
7914 return hasSameType(VarXTy->getElementType(), VarYTy->getElementType());
7915 }
7916 return false;
7917 }
7918
7919 // Namespaces with the same name and inlinedness match.
7920 if (const auto *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
7921 const auto *NamespaceY = cast<NamespaceDecl>(Y);
7922 return NamespaceX->isInline() == NamespaceY->isInline();
7923 }
7924
7925 // Identical template names and kinds match if their template parameter lists
7926 // and patterns match.
7927 if (const auto *TemplateX = dyn_cast<TemplateDecl>(X)) {
7928 const auto *TemplateY = cast<TemplateDecl>(Y);
7929
7930 // ConceptDecl wouldn't be the same if their constraint expression differs.
7931 if (const auto *ConceptX = dyn_cast<ConceptDecl>(X)) {
7932 const auto *ConceptY = cast<ConceptDecl>(Y);
7933 if (!isSameConstraintExpr(ConceptX->getConstraintExpr(),
7934 ConceptY->getConstraintExpr()))
7935 return false;
7936 }
7937
7938 return isSameEntity(TemplateX->getTemplatedDecl(),
7939 TemplateY->getTemplatedDecl()) &&
7940 isSameTemplateParameterList(TemplateX->getTemplateParameters(),
7941 TemplateY->getTemplateParameters());
7942 }
7943
7944 // Fields with the same name and the same type match.
7945 if (const auto *FDX = dyn_cast<FieldDecl>(X)) {
7946 const auto *FDY = cast<FieldDecl>(Y);
7947 // FIXME: Also check the bitwidth is odr-equivalent, if any.
7948 return hasSameType(FDX->getType(), FDY->getType());
7949 }
7950
7951 // Indirect fields with the same target field match.
7952 if (const auto *IFDX = dyn_cast<IndirectFieldDecl>(X)) {
7953 const auto *IFDY = cast<IndirectFieldDecl>(Y);
7954 return IFDX->getAnonField()->getCanonicalDecl() ==
7955 IFDY->getAnonField()->getCanonicalDecl();
7956 }
7957
7958 // Enumerators with the same name match.
7960 // FIXME: Also check the value is odr-equivalent.
7961 return true;
7962
7963 // Using shadow declarations with the same target match.
7964 if (const auto *USX = dyn_cast<UsingShadowDecl>(X)) {
7965 const auto *USY = cast<UsingShadowDecl>(Y);
7966 return declaresSameEntity(USX->getTargetDecl(), USY->getTargetDecl());
7967 }
7968
7969 // Using declarations with the same qualifier match. (We already know that
7970 // the name matches.)
7971 if (const auto *UX = dyn_cast<UsingDecl>(X)) {
7972 const auto *UY = cast<UsingDecl>(Y);
7973 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7974 UX->hasTypename() == UY->hasTypename() &&
7975 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7976 }
7977 if (const auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) {
7978 const auto *UY = cast<UnresolvedUsingValueDecl>(Y);
7979 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7980 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7981 }
7982 if (const auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X)) {
7983 return isSameQualifier(
7984 UX->getQualifier(),
7985 cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier());
7986 }
7987
7988 // Using-pack declarations are only created by instantiation, and match if
7989 // they're instantiated from matching UnresolvedUsing...Decls.
7990 if (const auto *UX = dyn_cast<UsingPackDecl>(X)) {
7991 return declaresSameEntity(
7992 UX->getInstantiatedFromUsingDecl(),
7993 cast<UsingPackDecl>(Y)->getInstantiatedFromUsingDecl());
7994 }
7995
7996 // Namespace alias definitions with the same target match.
7997 if (const auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) {
7998 const auto *NAY = cast<NamespaceAliasDecl>(Y);
7999 return NAX->getNamespace()->Equals(NAY->getNamespace());
8000 }
8001
8002 if (const auto *UX = dyn_cast<UsingEnumDecl>(X)) {
8003 const auto *UY = cast<UsingEnumDecl>(Y);
8004 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
8005 declaresSameEntity(UX->getEnumDecl(), UY->getEnumDecl());
8006 }
8007
8008 return false;
8009}
8010
8013 switch (Arg.getKind()) {
8015 return Arg;
8016
8018 return TemplateArgument(Arg.getAsExpr(), /*IsCanonical=*/true,
8019 Arg.getIsDefaulted());
8020
8022 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
8024 Arg.getIsDefaulted());
8025 }
8026
8029 /*isNullPtr*/ true, Arg.getIsDefaulted());
8030
8033 Arg.getIsDefaulted());
8034
8036 return TemplateArgument(
8039
8042
8044 return TemplateArgument(*this,
8047
8050 /*isNullPtr*/ false, Arg.getIsDefaulted());
8051
8053 bool AnyNonCanonArgs = false;
8054 auto CanonArgs = ::getCanonicalTemplateArguments(
8055 *this, Arg.pack_elements(), AnyNonCanonArgs);
8056 if (!AnyNonCanonArgs)
8057 return Arg;
8059 const_cast<ASTContext &>(*this), CanonArgs);
8060 NewArg.setIsDefaulted(Arg.getIsDefaulted());
8061 return NewArg;
8062 }
8063 }
8064
8065 // Silence GCC warning
8066 llvm_unreachable("Unhandled template argument kind");
8067}
8068
8070 const TemplateArgument &Arg2) const {
8071 if (Arg1.getKind() != Arg2.getKind())
8072 return false;
8073
8074 switch (Arg1.getKind()) {
8076 llvm_unreachable("Comparing NULL template argument");
8077
8079 return hasSameType(Arg1.getAsType(), Arg2.getAsType());
8080
8082 return Arg1.getAsDecl()->getUnderlyingDecl()->getCanonicalDecl() ==
8084
8086 return hasSameType(Arg1.getNullPtrType(), Arg2.getNullPtrType());
8087
8092
8094 return llvm::APSInt::isSameValue(Arg1.getAsIntegral(),
8095 Arg2.getAsIntegral());
8096
8098 return Arg1.structurallyEquals(Arg2);
8099
8101 llvm::FoldingSetNodeID ID1, ID2;
8102 Arg1.getAsExpr()->Profile(ID1, *this, /*Canonical=*/true);
8103 Arg2.getAsExpr()->Profile(ID2, *this, /*Canonical=*/true);
8104 return ID1 == ID2;
8105 }
8106
8108 return llvm::equal(
8109 Arg1.getPackAsArray(), Arg2.getPackAsArray(),
8110 [&](const TemplateArgument &Arg1, const TemplateArgument &Arg2) {
8111 return isSameTemplateArgument(Arg1, Arg2);
8112 });
8113 }
8114
8115 llvm_unreachable("Unhandled template argument kind");
8116}
8117
8119 // Handle the non-qualified case efficiently.
8120 if (!T.hasLocalQualifiers()) {
8121 // Handle the common positive case fast.
8122 if (const auto *AT = dyn_cast<ArrayType>(T))
8123 return AT;
8124 }
8125
8126 // Handle the common negative case fast.
8127 if (!isa<ArrayType>(T.getCanonicalType()))
8128 return nullptr;
8129
8130 // Apply any qualifiers from the array type to the element type. This
8131 // implements C99 6.7.3p8: "If the specification of an array type includes
8132 // any type qualifiers, the element type is so qualified, not the array type."
8133
8134 // If we get here, we either have type qualifiers on the type, or we have
8135 // sugar such as a typedef in the way. If we have type qualifiers on the type
8136 // we must propagate them down into the element type.
8137
8138 SplitQualType split = T.getSplitDesugaredType();
8139 Qualifiers qs = split.Quals;
8140
8141 // If we have a simple case, just return now.
8142 const auto *ATy = dyn_cast<ArrayType>(split.Ty);
8143 if (!ATy || qs.empty())
8144 return ATy;
8145
8146 // Otherwise, we have an array and we have qualifiers on it. Push the
8147 // qualifiers into the array element type and return a new array type.
8148 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
8149
8150 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
8151 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
8152 CAT->getSizeExpr(),
8153 CAT->getSizeModifier(),
8154 CAT->getIndexTypeCVRQualifiers()));
8155 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
8157 IAT->getSizeModifier(),
8158 IAT->getIndexTypeCVRQualifiers()));
8159
8160 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
8162 NewEltTy, DSAT->getSizeExpr(), DSAT->getSizeModifier(),
8163 DSAT->getIndexTypeCVRQualifiers()));
8164
8165 const auto *VAT = cast<VariableArrayType>(ATy);
8166 return cast<ArrayType>(
8167 getVariableArrayType(NewEltTy, VAT->getSizeExpr(), VAT->getSizeModifier(),
8168 VAT->getIndexTypeCVRQualifiers()));
8169}
8170
8172 if (getLangOpts().HLSL && T.getAddressSpace() == LangAS::hlsl_groupshared)
8173 return getLValueReferenceType(T);
8174 if (getLangOpts().HLSL && T->isConstantArrayType())
8175 return getArrayParameterType(T);
8176 if (T->isArrayType() || T->isFunctionType())
8177 return getDecayedType(T);
8178 return T;
8179}
8180
8184 return T.getUnqualifiedType();
8185}
8186
8188 // C++ [except.throw]p3:
8189 // A throw-expression initializes a temporary object, called the exception
8190 // object, the type of which is determined by removing any top-level
8191 // cv-qualifiers from the static type of the operand of throw and adjusting
8192 // the type from "array of T" or "function returning T" to "pointer to T"
8193 // or "pointer to function returning T", [...]
8195 if (T->isArrayType() || T->isFunctionType())
8196 T = getDecayedType(T);
8197 return T.getUnqualifiedType();
8198}
8199
8200/// getArrayDecayedType - Return the properly qualified result of decaying the
8201/// specified array type to a pointer. This operation is non-trivial when
8202/// handling typedefs etc. The canonical type of "T" must be an array type,
8203/// this returns a pointer to a properly qualified element of the array.
8204///
8205/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
8207 // Get the element type with 'getAsArrayType' so that we don't lose any
8208 // typedefs in the element type of the array. This also handles propagation
8209 // of type qualifiers from the array type into the element type if present
8210 // (C99 6.7.3p8).
8211 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
8212 assert(PrettyArrayType && "Not an array type!");
8213
8214 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
8215
8216 // int x[restrict 4] -> int *restrict
8218 PrettyArrayType->getIndexTypeQualifiers());
8219
8220 // int x[_Nullable] -> int * _Nullable
8221 if (auto Nullability = Ty->getNullability()) {
8222 Result = getAttributedType(*Nullability, Result, Result);
8223 }
8224 return Result;
8225}
8226
8228 return getBaseElementType(array->getElementType());
8229}
8230
8232 Qualifiers qs;
8233 while (true) {
8234 SplitQualType split = type.getSplitDesugaredType();
8235 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
8236 if (!array) break;
8237
8238 type = array->getElementType();
8240 }
8241
8242 return getQualifiedType(type, qs);
8243}
8244
8246 uint64_t ElementCount = 1;
8247 do {
8248 ElementCount *= CA->getZExtSize();
8249 CA = dyn_cast_if_present<ConstantArrayType>(
8251 } while (CA);
8252 return ElementCount;
8253}
8254
8255uint64_t
8257 if (!AILE)
8258 return 0;
8259
8260 uint64_t ElementCount = 1;
8261
8262 do {
8263 ElementCount *= AILE->getArraySize().getZExtValue();
8264 AILE = dyn_cast<ArrayInitLoopExpr>(AILE->getSubExpr());
8265 } while (AILE);
8266
8267 return ElementCount;
8268}
8269
8270/// getFloatingRank - Return a relative rank for floating point types.
8271/// This routine will assert if passed a built-in type that isn't a float.
8273 if (const auto *CT = T->getAs<ComplexType>())
8274 return getFloatingRank(CT->getElementType());
8275
8276 switch (T->castAs<BuiltinType>()->getKind()) {
8277 default: llvm_unreachable("getFloatingRank(): not a floating type");
8278 case BuiltinType::Float16: return Float16Rank;
8279 case BuiltinType::Half: return HalfRank;
8280 case BuiltinType::Float: return FloatRank;
8281 case BuiltinType::Double: return DoubleRank;
8282 case BuiltinType::LongDouble: return LongDoubleRank;
8283 case BuiltinType::Float128: return Float128Rank;
8284 case BuiltinType::BFloat16: return BFloat16Rank;
8285 case BuiltinType::Ibm128: return Ibm128Rank;
8286 }
8287}
8288
8289/// getFloatingTypeOrder - Compare the rank of the two specified floating
8290/// point types, ignoring the domain of the type (i.e. 'double' ==
8291/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
8292/// LHS < RHS, return -1.
8294 FloatingRank LHSR = getFloatingRank(LHS);
8295 FloatingRank RHSR = getFloatingRank(RHS);
8296
8297 if (LHSR == RHSR)
8298 return 0;
8299 if (LHSR > RHSR)
8300 return 1;
8301 return -1;
8302}
8303
8306 return 0;
8307 return getFloatingTypeOrder(LHS, RHS);
8308}
8309
8310/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
8311/// routine will assert if passed a built-in type that isn't an integer or enum,
8312/// or if it is not canonicalized.
8313unsigned ASTContext::getIntegerRank(const Type *T) const {
8314 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
8315
8316 // Results in this 'losing' to any type of the same size, but winning if
8317 // larger.
8318 if (const auto *EIT = dyn_cast<BitIntType>(T))
8319 return 0 + (EIT->getNumBits() << 3);
8320
8321 if (const auto *OBT = dyn_cast<OverflowBehaviorType>(T))
8322 return getIntegerRank(OBT->getUnderlyingType().getTypePtr());
8323
8324 switch (cast<BuiltinType>(T)->getKind()) {
8325 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
8326 case BuiltinType::Bool:
8327 return 1 + (getIntWidth(BoolTy) << 3);
8328 case BuiltinType::Char_S:
8329 case BuiltinType::Char_U:
8330 case BuiltinType::SChar:
8331 case BuiltinType::UChar:
8332 return 2 + (getIntWidth(CharTy) << 3);
8333 case BuiltinType::Short:
8334 case BuiltinType::UShort:
8335 return 3 + (getIntWidth(ShortTy) << 3);
8336 case BuiltinType::Int:
8337 case BuiltinType::UInt:
8338 return 4 + (getIntWidth(IntTy) << 3);
8339 case BuiltinType::Long:
8340 case BuiltinType::ULong:
8341 return 5 + (getIntWidth(LongTy) << 3);
8342 case BuiltinType::LongLong:
8343 case BuiltinType::ULongLong:
8344 return 6 + (getIntWidth(LongLongTy) << 3);
8345 case BuiltinType::Int128:
8346 case BuiltinType::UInt128:
8347 return 7 + (getIntWidth(Int128Ty) << 3);
8348
8349 // "The ranks of char8_t, char16_t, char32_t, and wchar_t equal the ranks of
8350 // their underlying types" [c++20 conv.rank]
8351 case BuiltinType::Char8:
8352 return getIntegerRank(UnsignedCharTy.getTypePtr());
8353 case BuiltinType::Char16:
8354 return getIntegerRank(
8355 getFromTargetType(Target->getChar16Type()).getTypePtr());
8356 case BuiltinType::Char32:
8357 return getIntegerRank(
8358 getFromTargetType(Target->getChar32Type()).getTypePtr());
8359 case BuiltinType::WChar_S:
8360 case BuiltinType::WChar_U:
8361 return getIntegerRank(
8362 getFromTargetType(Target->getWCharType()).getTypePtr());
8363 }
8364}
8365
8366/// Whether this is a promotable bitfield reference according
8367/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
8368///
8369/// \returns the type this bit-field will promote to, or NULL if no
8370/// promotion occurs.
8372 if (E->isTypeDependent() || E->isValueDependent())
8373 return {};
8374
8375 // C++ [conv.prom]p5:
8376 // If the bit-field has an enumerated type, it is treated as any other
8377 // value of that type for promotion purposes.
8379 return {};
8380
8381 // FIXME: We should not do this unless E->refersToBitField() is true. This
8382 // matters in C where getSourceBitField() will find bit-fields for various
8383 // cases where the source expression is not a bit-field designator.
8384
8385 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
8386 if (!Field)
8387 return {};
8388
8389 QualType FT = Field->getType();
8390
8391 uint64_t BitWidth = Field->getBitWidthValue();
8392 uint64_t IntSize = getTypeSize(IntTy);
8393 // C++ [conv.prom]p5:
8394 // A prvalue for an integral bit-field can be converted to a prvalue of type
8395 // int if int can represent all the values of the bit-field; otherwise, it
8396 // can be converted to unsigned int if unsigned int can represent all the
8397 // values of the bit-field. If the bit-field is larger yet, no integral
8398 // promotion applies to it.
8399 // C11 6.3.1.1/2:
8400 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
8401 // If an int can represent all values of the original type (as restricted by
8402 // the width, for a bit-field), the value is converted to an int; otherwise,
8403 // it is converted to an unsigned int.
8404 //
8405 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
8406 // We perform that promotion here to match GCC and C++.
8407 // FIXME: C does not permit promotion of an enum bit-field whose rank is
8408 // greater than that of 'int'. We perform that promotion to match GCC.
8409 //
8410 // C23 6.3.1.1p2:
8411 // The value from a bit-field of a bit-precise integer type is converted to
8412 // the corresponding bit-precise integer type. (The rest is the same as in
8413 // C11.)
8414 if (QualType QT = Field->getType(); QT->isBitIntType())
8415 return QT;
8416
8417 if (BitWidth < IntSize)
8418 return IntTy;
8419
8420 if (BitWidth == IntSize)
8421 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
8422
8423 // Bit-fields wider than int are not subject to promotions, and therefore act
8424 // like the base type. GCC has some weird bugs in this area that we
8425 // deliberately do not follow (GCC follows a pre-standard resolution to
8426 // C's DR315 which treats bit-width as being part of the type, and this leaks
8427 // into their semantics in some cases).
8428 return {};
8429}
8430
8431/// getPromotedIntegerType - Returns the type that Promotable will
8432/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
8433/// integer type.
8435 assert(!Promotable.isNull());
8436 assert(isPromotableIntegerType(Promotable));
8437 if (const auto *ED = Promotable->getAsEnumDecl())
8438 return ED->getPromotionType();
8439
8440 // OverflowBehaviorTypes promote their underlying type and preserve OBT
8441 // qualifier.
8442 if (const auto *OBT = Promotable->getAs<OverflowBehaviorType>()) {
8443 QualType PromotedUnderlying =
8444 getPromotedIntegerType(OBT->getUnderlyingType());
8445 return getOverflowBehaviorType(OBT->getBehaviorKind(), PromotedUnderlying);
8446 }
8447
8448 if (const auto *BT = Promotable->getAs<BuiltinType>()) {
8449 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
8450 // (3.9.1) can be converted to a prvalue of the first of the following
8451 // types that can represent all the values of its underlying type:
8452 // int, unsigned int, long int, unsigned long int, long long int, or
8453 // unsigned long long int [...]
8454 // FIXME: Is there some better way to compute this?
8455 if (BT->getKind() == BuiltinType::WChar_S ||
8456 BT->getKind() == BuiltinType::WChar_U ||
8457 BT->getKind() == BuiltinType::Char8 ||
8458 BT->getKind() == BuiltinType::Char16 ||
8459 BT->getKind() == BuiltinType::Char32) {
8460 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
8461 uint64_t FromSize = getTypeSize(BT);
8462 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
8464 for (const auto &PT : PromoteTypes) {
8465 uint64_t ToSize = getTypeSize(PT);
8466 if (FromSize < ToSize ||
8467 (FromSize == ToSize && FromIsSigned == PT->isSignedIntegerType()))
8468 return PT;
8469 }
8470 llvm_unreachable("char type should fit into long long");
8471 }
8472 }
8473
8474 // At this point, we should have a signed or unsigned integer type.
8475 if (Promotable->isSignedIntegerType())
8476 return IntTy;
8477 uint64_t PromotableSize = getIntWidth(Promotable);
8478 uint64_t IntSize = getIntWidth(IntTy);
8479 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
8480 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
8481}
8482
8483/// Recurses in pointer/array types until it finds an objc retainable
8484/// type and returns its ownership.
8486 while (!T.isNull()) {
8487 if (T.getObjCLifetime() != Qualifiers::OCL_None)
8488 return T.getObjCLifetime();
8489 if (T->isArrayType())
8491 else if (const auto *PT = T->getAs<PointerType>())
8492 T = PT->getPointeeType();
8493 else if (const auto *RT = T->getAs<ReferenceType>())
8494 T = RT->getPointeeType();
8495 else
8496 break;
8497 }
8498
8499 return Qualifiers::OCL_None;
8500}
8501
8502static const Type *getIntegerTypeForEnum(const EnumType *ET) {
8503 // Incomplete enum types are not treated as integer types.
8504 // FIXME: In C++, enum types are never integer types.
8505 const EnumDecl *ED = ET->getDecl()->getDefinitionOrSelf();
8506 if (ED->isComplete() && !ED->isScoped())
8507 return ED->getIntegerType().getTypePtr();
8508 return nullptr;
8509}
8510
8511/// getIntegerTypeOrder - Returns the highest ranked integer type:
8512/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
8513/// LHS < RHS, return -1.
8515 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
8516 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
8517
8518 // Unwrap enums to their underlying type.
8519 if (const auto *ET = dyn_cast<EnumType>(LHSC))
8520 LHSC = getIntegerTypeForEnum(ET);
8521 if (const auto *ET = dyn_cast<EnumType>(RHSC))
8522 RHSC = getIntegerTypeForEnum(ET);
8523
8524 if (LHSC == RHSC) return 0;
8525
8526 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
8527 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
8528
8529 unsigned LHSRank = getIntegerRank(LHSC);
8530 unsigned RHSRank = getIntegerRank(RHSC);
8531
8532 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
8533 if (LHSRank == RHSRank) return 0;
8534 return LHSRank > RHSRank ? 1 : -1;
8535 }
8536
8537 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
8538 if (LHSUnsigned) {
8539 // If the unsigned [LHS] type is larger, return it.
8540 if (LHSRank >= RHSRank)
8541 return 1;
8542
8543 // If the signed type can represent all values of the unsigned type, it
8544 // wins. Because we are dealing with 2's complement and types that are
8545 // powers of two larger than each other, this is always safe.
8546 return -1;
8547 }
8548
8549 // If the unsigned [RHS] type is larger, return it.
8550 if (RHSRank >= LHSRank)
8551 return -1;
8552
8553 // If the signed type can represent all values of the unsigned type, it
8554 // wins. Because we are dealing with 2's complement and types that are
8555 // powers of two larger than each other, this is always safe.
8556 return 1;
8557}
8558
8560 if (CFConstantStringTypeDecl)
8561 return CFConstantStringTypeDecl;
8562
8563 assert(!CFConstantStringTagDecl &&
8564 "tag and typedef should be initialized together");
8565 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
8566 CFConstantStringTagDecl->startDefinition();
8567
8568 struct {
8569 QualType Type;
8570 const char *Name;
8571 } Fields[5];
8572 unsigned Count = 0;
8573
8574 /// Objective-C ABI
8575 ///
8576 /// typedef struct __NSConstantString_tag {
8577 /// const int *isa;
8578 /// int flags;
8579 /// const char *str;
8580 /// long length;
8581 /// } __NSConstantString;
8582 ///
8583 /// Swift ABI (4.1, 4.2)
8584 ///
8585 /// typedef struct __NSConstantString_tag {
8586 /// uintptr_t _cfisa;
8587 /// uintptr_t _swift_rc;
8588 /// _Atomic(uint64_t) _cfinfoa;
8589 /// const char *_ptr;
8590 /// uint32_t _length;
8591 /// } __NSConstantString;
8592 ///
8593 /// Swift ABI (5.0)
8594 ///
8595 /// typedef struct __NSConstantString_tag {
8596 /// uintptr_t _cfisa;
8597 /// uintptr_t _swift_rc;
8598 /// _Atomic(uint64_t) _cfinfoa;
8599 /// const char *_ptr;
8600 /// uintptr_t _length;
8601 /// } __NSConstantString;
8602
8603 const auto CFRuntime = getLangOpts().CFRuntime;
8604 if (static_cast<unsigned>(CFRuntime) <
8605 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
8606 Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
8607 Fields[Count++] = { IntTy, "flags" };
8608 Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
8609 Fields[Count++] = { LongTy, "length" };
8610 } else {
8611 Fields[Count++] = { getUIntPtrType(), "_cfisa" };
8612 Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
8613 Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
8614 Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
8617 Fields[Count++] = { IntTy, "_ptr" };
8618 else
8619 Fields[Count++] = { getUIntPtrType(), "_ptr" };
8620 }
8621
8622 // Create fields
8623 for (unsigned i = 0; i < Count; ++i) {
8624 FieldDecl *Field =
8625 FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
8626 SourceLocation(), &Idents.get(Fields[i].Name),
8627 Fields[i].Type, /*TInfo=*/nullptr,
8628 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
8629 Field->setAccess(AS_public);
8630 CFConstantStringTagDecl->addDecl(Field);
8631 }
8632
8633 CFConstantStringTagDecl->completeDefinition();
8634 // This type is designed to be compatible with NSConstantString, but cannot
8635 // use the same name, since NSConstantString is an interface.
8636 CanQualType tagType = getCanonicalTagType(CFConstantStringTagDecl);
8637 CFConstantStringTypeDecl =
8638 buildImplicitTypedef(tagType, "__NSConstantString");
8639
8640 return CFConstantStringTypeDecl;
8641}
8642
8644 if (!CFConstantStringTagDecl)
8645 getCFConstantStringDecl(); // Build the tag and the typedef.
8646 return CFConstantStringTagDecl;
8647}
8648
8649// getCFConstantStringType - Return the type used for constant CFStrings.
8654
8656 if (ObjCSuperType.isNull()) {
8657 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
8658 getTranslationUnitDecl()->addDecl(ObjCSuperTypeDecl);
8659 ObjCSuperType = getCanonicalTagType(ObjCSuperTypeDecl);
8660 }
8661 return ObjCSuperType;
8662}
8663
8665 const auto *TT = T->castAs<TypedefType>();
8666 CFConstantStringTypeDecl = cast<TypedefDecl>(TT->getDecl());
8667 CFConstantStringTagDecl = TT->castAsRecordDecl();
8668}
8669
8671 if (BlockDescriptorType)
8672 return getCanonicalTagType(BlockDescriptorType);
8673
8674 RecordDecl *RD;
8675 // FIXME: Needs the FlagAppleBlock bit.
8676 RD = buildImplicitRecord("__block_descriptor");
8677 RD->startDefinition();
8678
8679 QualType FieldTypes[] = {
8682 };
8683
8684 static const char *const FieldNames[] = {
8685 "reserved",
8686 "Size"
8687 };
8688
8689 for (size_t i = 0; i < 2; ++i) {
8691 *this, RD, SourceLocation(), SourceLocation(),
8692 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
8693 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
8694 Field->setAccess(AS_public);
8695 RD->addDecl(Field);
8696 }
8697
8698 RD->completeDefinition();
8699
8700 BlockDescriptorType = RD;
8701
8702 return getCanonicalTagType(BlockDescriptorType);
8703}
8704
8706 if (BlockDescriptorExtendedType)
8707 return getCanonicalTagType(BlockDescriptorExtendedType);
8708
8709 RecordDecl *RD;
8710 // FIXME: Needs the FlagAppleBlock bit.
8711 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
8712 RD->startDefinition();
8713
8714 QualType FieldTypes[] = {
8719 };
8720
8721 static const char *const FieldNames[] = {
8722 "reserved",
8723 "Size",
8724 "CopyFuncPtr",
8725 "DestroyFuncPtr"
8726 };
8727
8728 for (size_t i = 0; i < 4; ++i) {
8730 *this, RD, SourceLocation(), SourceLocation(),
8731 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
8732 /*BitWidth=*/nullptr,
8733 /*Mutable=*/false, ICIS_NoInit);
8734 Field->setAccess(AS_public);
8735 RD->addDecl(Field);
8736 }
8737
8738 RD->completeDefinition();
8739
8740 BlockDescriptorExtendedType = RD;
8741 return getCanonicalTagType(BlockDescriptorExtendedType);
8742}
8743
8745 const auto *BT = dyn_cast<BuiltinType>(T);
8746
8747 if (!BT) {
8748 if (isa<PipeType>(T))
8749 return OCLTK_Pipe;
8750
8751 return OCLTK_Default;
8752 }
8753
8754 switch (BT->getKind()) {
8755#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8756 case BuiltinType::Id: \
8757 return OCLTK_Image;
8758#include "clang/Basic/OpenCLImageTypes.def"
8759
8760 case BuiltinType::OCLClkEvent:
8761 return OCLTK_ClkEvent;
8762
8763 case BuiltinType::OCLEvent:
8764 return OCLTK_Event;
8765
8766 case BuiltinType::OCLQueue:
8767 return OCLTK_Queue;
8768
8769 case BuiltinType::OCLReserveID:
8770 return OCLTK_ReserveID;
8771
8772 case BuiltinType::OCLSampler:
8773 return OCLTK_Sampler;
8774
8775 default:
8776 return OCLTK_Default;
8777 }
8778}
8779
8781 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
8782}
8783
8784/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
8785/// requires copy/dispose. Note that this must match the logic
8786/// in buildByrefHelpers.
8788 const VarDecl *D) {
8789 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
8790 const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
8791 if (!copyExpr && record->hasTrivialDestructor()) return false;
8792
8793 return true;
8794 }
8795
8797 return true;
8798
8799 // The block needs copy/destroy helpers if Ty is non-trivial to destructively
8800 // move or destroy.
8802 return true;
8803
8804 if (!Ty->isObjCRetainableType()) return false;
8805
8806 Qualifiers qs = Ty.getQualifiers();
8807
8808 // If we have lifetime, that dominates.
8809 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
8810 switch (lifetime) {
8811 case Qualifiers::OCL_None: llvm_unreachable("impossible");
8812
8813 // These are just bits as far as the runtime is concerned.
8816 return false;
8817
8818 // These cases should have been taken care of when checking the type's
8819 // non-triviality.
8822 llvm_unreachable("impossible");
8823 }
8824 llvm_unreachable("fell out of lifetime switch!");
8825 }
8826 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
8828}
8829
8831 Qualifiers::ObjCLifetime &LifeTime,
8832 bool &HasByrefExtendedLayout) const {
8833 if (!getLangOpts().ObjC ||
8834 getLangOpts().getGC() != LangOptions::NonGC)
8835 return false;
8836
8837 HasByrefExtendedLayout = false;
8838 if (Ty->isRecordType()) {
8839 HasByrefExtendedLayout = true;
8840 LifeTime = Qualifiers::OCL_None;
8841 } else if ((LifeTime = Ty.getObjCLifetime())) {
8842 // Honor the ARC qualifiers.
8843 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
8844 // The MRR rule.
8846 } else {
8847 LifeTime = Qualifiers::OCL_None;
8848 }
8849 return true;
8850}
8851
8853 assert(Target && "Expected target to be initialized");
8854 const llvm::Triple &T = Target->getTriple();
8855 // Windows is LLP64 rather than LP64
8856 if (T.isOSWindows() && T.isArch64Bit())
8857 return UnsignedLongLongTy;
8858 return UnsignedLongTy;
8859}
8860
8862 assert(Target && "Expected target to be initialized");
8863 const llvm::Triple &T = Target->getTriple();
8864 // Windows is LLP64 rather than LP64
8865 if (T.isOSWindows() && T.isArch64Bit())
8866 return LongLongTy;
8867 return LongTy;
8868}
8869
8871 if (!ObjCInstanceTypeDecl)
8872 ObjCInstanceTypeDecl =
8873 buildImplicitTypedef(getObjCIdType(), "instancetype");
8874 return ObjCInstanceTypeDecl;
8875}
8876
8877// This returns true if a type has been typedefed to BOOL:
8878// typedef <type> BOOL;
8880 if (const auto *TT = dyn_cast<TypedefType>(T))
8881 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
8882 return II->isStr("BOOL");
8883
8884 return false;
8885}
8886
8887/// getObjCEncodingTypeSize returns size of type for objective-c encoding
8888/// purpose.
8890 if (!type->isIncompleteArrayType() && type->isIncompleteType())
8891 return CharUnits::Zero();
8892
8894
8895 // Make all integer and enum types at least as large as an int
8896 if (sz.isPositive() && type->isIntegralOrEnumerationType())
8897 sz = std::max(sz, getTypeSizeInChars(IntTy));
8898 // Treat arrays as pointers, since that's how they're passed in.
8899 else if (type->isArrayType())
8901 return sz;
8902}
8903
8910
8913 if (!VD->isInline())
8915
8916 // In almost all cases, it's a weak definition.
8917 auto *First = VD->getFirstDecl();
8918 if (First->isInlineSpecified() || !First->isStaticDataMember())
8920
8921 // If there's a file-context declaration in this translation unit, it's a
8922 // non-discardable definition.
8923 for (auto *D : VD->redecls())
8925 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
8927
8928 // If we've not seen one yet, we don't know.
8930}
8931
8932static std::string charUnitsToString(CharUnits CU) {
8933 return llvm::itostr(CU.getQuantity());
8934}
8935
8936/// getObjCEncodingForBlock - Return the encoded type for this block
8937/// declaration.
8939 std::string S;
8940
8941 const BlockDecl *Decl = Expr->getBlockDecl();
8942 QualType BlockTy =
8944 QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType();
8945 // Encode result type.
8946 if (getLangOpts().EncodeExtendedBlockSig)
8948 true /*Extended*/);
8949 else
8950 getObjCEncodingForType(BlockReturnTy, S);
8951 // Compute size of all parameters.
8952 // Start with computing size of a pointer in number of bytes.
8953 // FIXME: There might(should) be a better way of doing this computation!
8955 CharUnits ParmOffset = PtrSize;
8956 for (auto *PI : Decl->parameters()) {
8957 QualType PType = PI->getType();
8959 if (sz.isZero())
8960 continue;
8961 assert(sz.isPositive() && "BlockExpr - Incomplete param type");
8962 ParmOffset += sz;
8963 }
8964 // Size of the argument frame
8965 S += charUnitsToString(ParmOffset);
8966 // Block pointer and offset.
8967 S += "@?0";
8968
8969 // Argument types.
8970 ParmOffset = PtrSize;
8971 for (auto *PVDecl : Decl->parameters()) {
8972 QualType PType = PVDecl->getOriginalType();
8973 if (const auto *AT =
8974 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8975 // Use array's original type only if it has known number of
8976 // elements.
8977 if (!isa<ConstantArrayType>(AT))
8978 PType = PVDecl->getType();
8979 } else if (PType->isFunctionType())
8980 PType = PVDecl->getType();
8981 if (getLangOpts().EncodeExtendedBlockSig)
8983 S, true /*Extended*/);
8984 else
8985 getObjCEncodingForType(PType, S);
8986 S += charUnitsToString(ParmOffset);
8987 ParmOffset += getObjCEncodingTypeSize(PType);
8988 }
8989
8990 return S;
8991}
8992
8993std::string
8995 std::string S;
8996 // Encode result type.
8997 getObjCEncodingForType(Decl->getReturnType(), S);
8998 CharUnits ParmOffset;
8999 // Compute size of all parameters.
9000 for (auto *PI : Decl->parameters()) {
9001 QualType PType = PI->getType();
9003 if (sz.isZero())
9004 continue;
9005
9006 assert(sz.isPositive() &&
9007 "getObjCEncodingForFunctionDecl - Incomplete param type");
9008 ParmOffset += sz;
9009 }
9010 S += charUnitsToString(ParmOffset);
9011 ParmOffset = CharUnits::Zero();
9012
9013 // Argument types.
9014 for (auto *PVDecl : Decl->parameters()) {
9015 QualType PType = PVDecl->getOriginalType();
9016 if (const auto *AT =
9017 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
9018 // Use array's original type only if it has known number of
9019 // elements.
9020 if (!isa<ConstantArrayType>(AT))
9021 PType = PVDecl->getType();
9022 } else if (PType->isFunctionType())
9023 PType = PVDecl->getType();
9024 getObjCEncodingForType(PType, S);
9025 S += charUnitsToString(ParmOffset);
9026 ParmOffset += getObjCEncodingTypeSize(PType);
9027 }
9028
9029 return S;
9030}
9031
9032/// getObjCEncodingForMethodParameter - Return the encoded type for a single
9033/// method parameter or return type. If Extended, include class names and
9034/// block object types.
9036 QualType T, std::string& S,
9037 bool Extended) const {
9038 // Encode type qualifier, 'in', 'inout', etc. for the parameter.
9040 // Encode parameter type.
9041 ObjCEncOptions Options = ObjCEncOptions()
9042 .setExpandPointedToStructures()
9043 .setExpandStructures()
9044 .setIsOutermostType();
9045 if (Extended)
9046 Options.setEncodeBlockParameters().setEncodeClassNames();
9047 getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr);
9048}
9049
9050/// getObjCEncodingForMethodDecl - Return the encoded type for this method
9051/// declaration.
9053 bool Extended) const {
9054 // FIXME: This is not very efficient.
9055 // Encode return type.
9056 std::string S;
9057 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
9058 Decl->getReturnType(), S, Extended);
9059 // Compute size of all parameters.
9060 // Start with computing size of a pointer in number of bytes.
9061 // FIXME: There might(should) be a better way of doing this computation!
9063 // The first two arguments (self and _cmd) are pointers; account for
9064 // their size.
9065 CharUnits ParmOffset = 2 * PtrSize;
9066 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
9067 E = Decl->sel_param_end(); PI != E; ++PI) {
9068 QualType PType = (*PI)->getType();
9070 if (sz.isZero())
9071 continue;
9072
9073 assert(sz.isPositive() &&
9074 "getObjCEncodingForMethodDecl - Incomplete param type");
9075 ParmOffset += sz;
9076 }
9077 S += charUnitsToString(ParmOffset);
9078 S += "@0:";
9079 S += charUnitsToString(PtrSize);
9080
9081 // Argument types.
9082 ParmOffset = 2 * PtrSize;
9083 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
9084 E = Decl->sel_param_end(); PI != E; ++PI) {
9085 const ParmVarDecl *PVDecl = *PI;
9086 QualType PType = PVDecl->getOriginalType();
9087 if (const auto *AT =
9088 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
9089 // Use array's original type only if it has known number of
9090 // elements.
9091 if (!isa<ConstantArrayType>(AT))
9092 PType = PVDecl->getType();
9093 } else if (PType->isFunctionType())
9094 PType = PVDecl->getType();
9096 PType, S, Extended);
9097 S += charUnitsToString(ParmOffset);
9098 ParmOffset += getObjCEncodingTypeSize(PType);
9099 }
9100
9101 return S;
9102}
9103
9106 const ObjCPropertyDecl *PD,
9107 const Decl *Container) const {
9108 if (!Container)
9109 return nullptr;
9110 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
9111 for (auto *PID : CID->property_impls())
9112 if (PID->getPropertyDecl() == PD)
9113 return PID;
9114 } else {
9115 const auto *OID = cast<ObjCImplementationDecl>(Container);
9116 for (auto *PID : OID->property_impls())
9117 if (PID->getPropertyDecl() == PD)
9118 return PID;
9119 }
9120 return nullptr;
9121}
9122
9123/// getObjCEncodingForPropertyDecl - Return the encoded type for this
9124/// property declaration. If non-NULL, Container must be either an
9125/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
9126/// NULL when getting encodings for protocol properties.
9127/// Property attributes are stored as a comma-delimited C string. The simple
9128/// attributes readonly and bycopy are encoded as single characters. The
9129/// parametrized attributes, getter=name, setter=name, and ivar=name, are
9130/// encoded as single characters, followed by an identifier. Property types
9131/// are also encoded as a parametrized attribute. The characters used to encode
9132/// these attributes are defined by the following enumeration:
9133/// @code
9134/// enum PropertyAttributes {
9135/// kPropertyReadOnly = 'R', // property is read-only.
9136/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
9137/// kPropertyByref = '&', // property is a reference to the value last assigned
9138/// kPropertyDynamic = 'D', // property is dynamic
9139/// kPropertyGetter = 'G', // followed by getter selector name
9140/// kPropertySetter = 'S', // followed by setter selector name
9141/// kPropertyInstanceVariable = 'V' // followed by instance variable name
9142/// kPropertyType = 'T' // followed by old-style type encoding.
9143/// kPropertyWeak = 'W' // 'weak' property
9144/// kPropertyStrong = 'P' // property GC'able
9145/// kPropertyNonAtomic = 'N' // property non-atomic
9146/// kPropertyOptional = '?' // property optional
9147/// };
9148/// @endcode
9149std::string
9151 const Decl *Container) const {
9152 // Collect information from the property implementation decl(s).
9153 bool Dynamic = false;
9154 ObjCPropertyImplDecl *SynthesizePID = nullptr;
9155
9156 if (ObjCPropertyImplDecl *PropertyImpDecl =
9158 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
9159 Dynamic = true;
9160 else
9161 SynthesizePID = PropertyImpDecl;
9162 }
9163
9164 // FIXME: This is not very efficient.
9165 std::string S = "T";
9166
9167 // Encode result type.
9168 // GCC has some special rules regarding encoding of properties which
9169 // closely resembles encoding of ivars.
9171
9172 if (PD->isOptional())
9173 S += ",?";
9174
9175 if (PD->isReadOnly()) {
9176 S += ",R";
9178 S += ",C";
9180 S += ",&";
9182 S += ",W";
9183 } else {
9184 switch (PD->getSetterKind()) {
9185 case ObjCPropertyDecl::Assign: break;
9186 case ObjCPropertyDecl::Copy: S += ",C"; break;
9187 case ObjCPropertyDecl::Retain: S += ",&"; break;
9188 case ObjCPropertyDecl::Weak: S += ",W"; break;
9189 }
9190 }
9191
9192 // It really isn't clear at all what this means, since properties
9193 // are "dynamic by default".
9194 if (Dynamic)
9195 S += ",D";
9196
9198 S += ",N";
9199
9201 S += ",G";
9202 S += PD->getGetterName().getAsString();
9203 }
9204
9206 S += ",S";
9207 S += PD->getSetterName().getAsString();
9208 }
9209
9210 if (SynthesizePID) {
9211 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
9212 S += ",V";
9213 S += OID->getNameAsString();
9214 }
9215
9216 // FIXME: OBJCGC: weak & strong
9217 return S;
9218}
9219
9220/// getLegacyIntegralTypeEncoding -
9221/// Another legacy compatibility encoding: 32-bit longs are encoded as
9222/// 'l' or 'L' , but not always. For typedefs, we need to use
9223/// 'i' or 'I' instead if encoding a struct field, or a pointer!
9225 if (PointeeTy->getAs<TypedefType>()) {
9226 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
9227 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
9228 PointeeTy = UnsignedIntTy;
9229 else
9230 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
9231 PointeeTy = IntTy;
9232 }
9233 }
9234}
9235
9237 const FieldDecl *Field,
9238 QualType *NotEncodedT) const {
9239 // We follow the behavior of gcc, expanding structures which are
9240 // directly pointed to, and expanding embedded structures. Note that
9241 // these rules are sufficient to prevent recursive encoding of the
9242 // same type.
9243 getObjCEncodingForTypeImpl(T, S,
9244 ObjCEncOptions()
9245 .setExpandPointedToStructures()
9246 .setExpandStructures()
9247 .setIsOutermostType(),
9248 Field, NotEncodedT);
9249}
9250
9252 std::string& S) const {
9253 // Encode result type.
9254 // GCC has some special rules regarding encoding of properties which
9255 // closely resembles encoding of ivars.
9256 getObjCEncodingForTypeImpl(T, S,
9257 ObjCEncOptions()
9258 .setExpandPointedToStructures()
9259 .setExpandStructures()
9260 .setIsOutermostType()
9261 .setEncodingProperty(),
9262 /*Field=*/nullptr);
9263}
9264
9266 const BuiltinType *BT) {
9268 switch (kind) {
9269 case BuiltinType::Void: return 'v';
9270 case BuiltinType::Bool: return 'B';
9271 case BuiltinType::Char8:
9272 case BuiltinType::Char_U:
9273 case BuiltinType::UChar: return 'C';
9274 case BuiltinType::Char16:
9275 case BuiltinType::UShort: return 'S';
9276 case BuiltinType::Char32:
9277 case BuiltinType::UInt: return 'I';
9278 case BuiltinType::ULong:
9279 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
9280 case BuiltinType::UInt128: return 'T';
9281 case BuiltinType::ULongLong: return 'Q';
9282 case BuiltinType::Char_S:
9283 case BuiltinType::SChar: return 'c';
9284 case BuiltinType::Short: return 's';
9285 case BuiltinType::WChar_S:
9286 case BuiltinType::WChar_U:
9287 case BuiltinType::Int: return 'i';
9288 case BuiltinType::Long:
9289 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
9290 case BuiltinType::LongLong: return 'q';
9291 case BuiltinType::Int128: return 't';
9292 case BuiltinType::Float: return 'f';
9293 case BuiltinType::Double: return 'd';
9294 case BuiltinType::LongDouble: return 'D';
9295 case BuiltinType::NullPtr: return '*'; // like char*
9296
9297 case BuiltinType::BFloat16:
9298 case BuiltinType::Float16:
9299 case BuiltinType::Float128:
9300 case BuiltinType::Ibm128:
9301 case BuiltinType::Half:
9302 case BuiltinType::ShortAccum:
9303 case BuiltinType::Accum:
9304 case BuiltinType::LongAccum:
9305 case BuiltinType::UShortAccum:
9306 case BuiltinType::UAccum:
9307 case BuiltinType::ULongAccum:
9308 case BuiltinType::ShortFract:
9309 case BuiltinType::Fract:
9310 case BuiltinType::LongFract:
9311 case BuiltinType::UShortFract:
9312 case BuiltinType::UFract:
9313 case BuiltinType::ULongFract:
9314 case BuiltinType::SatShortAccum:
9315 case BuiltinType::SatAccum:
9316 case BuiltinType::SatLongAccum:
9317 case BuiltinType::SatUShortAccum:
9318 case BuiltinType::SatUAccum:
9319 case BuiltinType::SatULongAccum:
9320 case BuiltinType::SatShortFract:
9321 case BuiltinType::SatFract:
9322 case BuiltinType::SatLongFract:
9323 case BuiltinType::SatUShortFract:
9324 case BuiltinType::SatUFract:
9325 case BuiltinType::SatULongFract:
9326 // FIXME: potentially need @encodes for these!
9327 return ' ';
9328
9329#define SVE_TYPE(Name, Id, SingletonId) \
9330 case BuiltinType::Id:
9331#include "clang/Basic/AArch64ACLETypes.def"
9332#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9333#include "clang/Basic/RISCVVTypes.def"
9334#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9335#include "clang/Basic/WebAssemblyReferenceTypes.def"
9336#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
9337#include "clang/Basic/AMDGPUTypes.def"
9338#define SPIRV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9339#include "clang/Basic/SPIRVTypes.def"
9340 {
9341 DiagnosticsEngine &Diags = C->getDiagnostics();
9342 Diags.Report(diag::err_unsupported_objc_primitive_encoding)
9343 << QualType(BT, 0);
9344 return ' ';
9345 }
9346
9347 case BuiltinType::ObjCId:
9348 case BuiltinType::ObjCClass:
9349 case BuiltinType::ObjCSel:
9350 llvm_unreachable("@encoding ObjC primitive type");
9351
9352 // OpenCL and placeholder types don't need @encodings.
9353#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
9354 case BuiltinType::Id:
9355#include "clang/Basic/OpenCLImageTypes.def"
9356#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
9357 case BuiltinType::Id:
9358#include "clang/Basic/OpenCLExtensionTypes.def"
9359 case BuiltinType::OCLEvent:
9360 case BuiltinType::OCLClkEvent:
9361 case BuiltinType::OCLQueue:
9362 case BuiltinType::OCLReserveID:
9363 case BuiltinType::OCLSampler:
9364 case BuiltinType::Dependent:
9365 case BuiltinType::MetaInfo:
9366#define PPC_VECTOR_TYPE(Name, Id, Size) \
9367 case BuiltinType::Id:
9368#include "clang/Basic/PPCTypes.def"
9369#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9370#include "clang/Basic/HLSLIntangibleTypes.def"
9371#define HLSL_PACKED_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9372#include "clang/Basic/HLSLPackedTypes.def"
9373#define BUILTIN_TYPE(KIND, ID)
9374#define PLACEHOLDER_TYPE(KIND, ID) \
9375 case BuiltinType::KIND:
9376#include "clang/AST/BuiltinTypes.def"
9377 llvm_unreachable("invalid builtin type for @encode");
9378 }
9379 llvm_unreachable("invalid BuiltinType::Kind value");
9380}
9381
9382static char ObjCEncodingForEnumDecl(const ASTContext *C, const EnumDecl *ED) {
9384
9385 // The encoding of an non-fixed enum type is always 'i', regardless of size.
9386 if (!Enum->isFixed())
9387 return 'i';
9388
9389 // The encoding of a fixed enum type matches its fixed underlying type.
9390 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
9392}
9393
9394static void EncodeBitField(const ASTContext *Ctx, std::string& S,
9395 QualType T, const FieldDecl *FD) {
9396 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
9397 S += 'b';
9398 // The NeXT runtime encodes bit fields as b followed by the number of bits.
9399 // The GNU runtime requires more information; bitfields are encoded as b,
9400 // then the offset (in bits) of the first element, then the type of the
9401 // bitfield, then the size in bits. For example, in this structure:
9402 //
9403 // struct
9404 // {
9405 // int integer;
9406 // int flags:2;
9407 // };
9408 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
9409 // runtime, but b32i2 for the GNU runtime. The reason for this extra
9410 // information is not especially sensible, but we're stuck with it for
9411 // compatibility with GCC, although providing it breaks anything that
9412 // actually uses runtime introspection and wants to work on both runtimes...
9413 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
9414 uint64_t Offset;
9415
9416 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
9417 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), IVD);
9418 } else {
9419 const RecordDecl *RD = FD->getParent();
9420 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
9421 Offset = RL.getFieldOffset(FD->getFieldIndex());
9422 }
9423
9424 S += llvm::utostr(Offset);
9425
9426 if (const auto *ET = T->getAsCanonical<EnumType>())
9427 S += ObjCEncodingForEnumDecl(Ctx, ET->getDecl());
9428 else {
9429 const auto *BT = T->castAs<BuiltinType>();
9430 S += getObjCEncodingForPrimitiveType(Ctx, BT);
9431 }
9432 }
9433 S += llvm::utostr(FD->getBitWidthValue());
9434}
9435
9436// Helper function for determining whether the encoded type string would include
9437// a template specialization type.
9439 bool VisitBasesAndFields) {
9440 T = T->getBaseElementTypeUnsafe();
9441
9442 if (auto *PT = T->getAs<PointerType>())
9444 PT->getPointeeType().getTypePtr(), false);
9445
9446 auto *CXXRD = T->getAsCXXRecordDecl();
9447
9448 if (!CXXRD)
9449 return false;
9450
9452 return true;
9453
9454 if (!CXXRD->hasDefinition() || !VisitBasesAndFields)
9455 return false;
9456
9457 for (const auto &B : CXXRD->bases())
9458 if (hasTemplateSpecializationInEncodedString(B.getType().getTypePtr(),
9459 true))
9460 return true;
9461
9462 for (auto *FD : CXXRD->fields())
9463 if (hasTemplateSpecializationInEncodedString(FD->getType().getTypePtr(),
9464 true))
9465 return true;
9466
9467 return false;
9468}
9469
9470// FIXME: Use SmallString for accumulating string.
9471void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
9472 const ObjCEncOptions Options,
9473 const FieldDecl *FD,
9474 QualType *NotEncodedT) const {
9476 switch (CT->getTypeClass()) {
9477 case Type::Builtin:
9478 case Type::Enum:
9479 if (FD && FD->isBitField())
9480 return EncodeBitField(this, S, T, FD);
9481 if (const auto *BT = dyn_cast<BuiltinType>(CT))
9482 S += getObjCEncodingForPrimitiveType(this, BT);
9483 else
9484 S += ObjCEncodingForEnumDecl(this, cast<EnumType>(CT)->getDecl());
9485 return;
9486
9487 case Type::Complex:
9488 S += 'j';
9489 getObjCEncodingForTypeImpl(T->castAs<ComplexType>()->getElementType(), S,
9490 ObjCEncOptions(),
9491 /*Field=*/nullptr);
9492 return;
9493
9494 case Type::Atomic:
9495 S += 'A';
9496 getObjCEncodingForTypeImpl(T->castAs<AtomicType>()->getValueType(), S,
9497 ObjCEncOptions(),
9498 /*Field=*/nullptr);
9499 return;
9500
9501 // encoding for pointer or reference types.
9502 case Type::Pointer:
9503 case Type::LValueReference:
9504 case Type::RValueReference: {
9505 QualType PointeeTy;
9506 if (isa<PointerType>(CT)) {
9507 const auto *PT = T->castAs<PointerType>();
9508 if (PT->isObjCSelType()) {
9509 S += ':';
9510 return;
9511 }
9512 PointeeTy = PT->getPointeeType();
9513 } else {
9514 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
9515 }
9516
9517 bool isReadOnly = false;
9518 // For historical/compatibility reasons, the read-only qualifier of the
9519 // pointee gets emitted _before_ the '^'. The read-only qualifier of
9520 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
9521 // Also, do not emit the 'r' for anything but the outermost type!
9522 if (T->getAs<TypedefType>()) {
9523 if (Options.IsOutermostType() && T.isConstQualified()) {
9524 isReadOnly = true;
9525 S += 'r';
9526 }
9527 } else if (Options.IsOutermostType()) {
9528 QualType P = PointeeTy;
9529 while (auto PT = P->getAs<PointerType>())
9530 P = PT->getPointeeType();
9531 if (P.isConstQualified()) {
9532 isReadOnly = true;
9533 S += 'r';
9534 }
9535 }
9536 if (isReadOnly) {
9537 // Another legacy compatibility encoding. Some ObjC qualifier and type
9538 // combinations need to be rearranged.
9539 // Rewrite "in const" from "nr" to "rn"
9540 if (StringRef(S).ends_with("nr"))
9541 S.replace(S.end()-2, S.end(), "rn");
9542 }
9543
9544 if (PointeeTy->isCharType()) {
9545 // char pointer types should be encoded as '*' unless it is a
9546 // type that has been typedef'd to 'BOOL'.
9547 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
9548 S += '*';
9549 return;
9550 }
9551 } else if (const auto *RTy = PointeeTy->getAsCanonical<RecordType>()) {
9552 const IdentifierInfo *II = RTy->getDecl()->getIdentifier();
9553 // GCC binary compat: Need to convert "struct objc_class *" to "#".
9554 if (II == &Idents.get("objc_class")) {
9555 S += '#';
9556 return;
9557 }
9558 // GCC binary compat: Need to convert "struct objc_object *" to "@".
9559 if (II == &Idents.get("objc_object")) {
9560 S += '@';
9561 return;
9562 }
9563 // If the encoded string for the class includes template names, just emit
9564 // "^v" for pointers to the class.
9565 if (getLangOpts().CPlusPlus &&
9566 (!getLangOpts().EncodeCXXClassTemplateSpec &&
9568 RTy, Options.ExpandPointedToStructures()))) {
9569 S += "^v";
9570 return;
9571 }
9572 // fall through...
9573 }
9574 S += '^';
9576
9577 ObjCEncOptions NewOptions;
9578 if (Options.ExpandPointedToStructures())
9579 NewOptions.setExpandStructures();
9580 getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions,
9581 /*Field=*/nullptr, NotEncodedT);
9582 return;
9583 }
9584
9585 case Type::ConstantArray:
9586 case Type::IncompleteArray:
9587 case Type::VariableArray: {
9588 const auto *AT = cast<ArrayType>(CT);
9589
9590 if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) {
9591 // Incomplete arrays are encoded as a pointer to the array element.
9592 S += '^';
9593
9594 getObjCEncodingForTypeImpl(
9595 AT->getElementType(), S,
9596 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD);
9597 } else {
9598 S += '[';
9599
9600 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
9601 S += llvm::utostr(CAT->getZExtSize());
9602 else {
9603 //Variable length arrays are encoded as a regular array with 0 elements.
9605 "Unknown array type!");
9606 S += '0';
9607 }
9608
9609 getObjCEncodingForTypeImpl(
9610 AT->getElementType(), S,
9611 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD,
9612 NotEncodedT);
9613 S += ']';
9614 }
9615 return;
9616 }
9617
9618 case Type::FunctionNoProto:
9619 case Type::FunctionProto:
9620 S += '?';
9621 return;
9622
9623 case Type::Record: {
9624 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
9625 S += RDecl->isUnion() ? '(' : '{';
9626 // Anonymous structures print as '?'
9627 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
9628 S += II->getName();
9629 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
9630 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
9631 llvm::raw_string_ostream OS(S);
9632 printTemplateArgumentList(OS, TemplateArgs.asArray(),
9634 }
9635 } else {
9636 S += '?';
9637 }
9638 if (Options.ExpandStructures()) {
9639 S += '=';
9640 if (!RDecl->isUnion()) {
9641 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
9642 } else {
9643 for (const auto *Field : RDecl->fields()) {
9644 if (FD) {
9645 S += '"';
9646 S += Field->getNameAsString();
9647 S += '"';
9648 }
9649
9650 // Special case bit-fields.
9651 if (Field->isBitField()) {
9652 getObjCEncodingForTypeImpl(Field->getType(), S,
9653 ObjCEncOptions().setExpandStructures(),
9654 Field);
9655 } else {
9656 QualType qt = Field->getType();
9658 getObjCEncodingForTypeImpl(
9659 qt, S,
9660 ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
9661 NotEncodedT);
9662 }
9663 }
9664 }
9665 }
9666 S += RDecl->isUnion() ? ')' : '}';
9667 return;
9668 }
9669
9670 case Type::BlockPointer: {
9671 const auto *BT = T->castAs<BlockPointerType>();
9672 S += "@?"; // Unlike a pointer-to-function, which is "^?".
9673 if (Options.EncodeBlockParameters()) {
9674 const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
9675
9676 S += '<';
9677 // Block return type
9678 getObjCEncodingForTypeImpl(FT->getReturnType(), S,
9679 Options.forComponentType(), FD, NotEncodedT);
9680 // Block self
9681 S += "@?";
9682 // Block parameters
9683 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
9684 for (const auto &I : FPT->param_types())
9685 getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD,
9686 NotEncodedT);
9687 }
9688 S += '>';
9689 }
9690 return;
9691 }
9692
9693 case Type::ObjCObject: {
9694 // hack to match legacy encoding of *id and *Class
9695 QualType Ty = getObjCObjectPointerType(CT);
9696 if (Ty->isObjCIdType()) {
9697 S += "{objc_object=}";
9698 return;
9699 }
9700 else if (Ty->isObjCClassType()) {
9701 S += "{objc_class=}";
9702 return;
9703 }
9704 // TODO: Double check to make sure this intentionally falls through.
9705 [[fallthrough]];
9706 }
9707
9708 case Type::ObjCInterface: {
9709 // Ignore protocol qualifiers when mangling at this level.
9710 // @encode(class_name)
9711 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
9712 S += '{';
9713 S += OI->getObjCRuntimeNameAsString();
9714 if (Options.ExpandStructures()) {
9715 S += '=';
9716 SmallVector<const ObjCIvarDecl*, 32> Ivars;
9717 DeepCollectObjCIvars(OI, true, Ivars);
9718 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
9719 const FieldDecl *Field = Ivars[i];
9720 if (Field->isBitField())
9721 getObjCEncodingForTypeImpl(Field->getType(), S,
9722 ObjCEncOptions().setExpandStructures(),
9723 Field);
9724 else
9725 getObjCEncodingForTypeImpl(Field->getType(), S,
9726 ObjCEncOptions().setExpandStructures(), FD,
9727 NotEncodedT);
9728 }
9729 }
9730 S += '}';
9731 return;
9732 }
9733
9734 case Type::ObjCObjectPointer: {
9735 const auto *OPT = T->castAs<ObjCObjectPointerType>();
9736 if (OPT->isObjCIdType()) {
9737 S += '@';
9738 return;
9739 }
9740
9741 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
9742 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
9743 // Since this is a binary compatibility issue, need to consult with
9744 // runtime folks. Fortunately, this is a *very* obscure construct.
9745 S += '#';
9746 return;
9747 }
9748
9749 if (OPT->isObjCQualifiedIdType()) {
9750 getObjCEncodingForTypeImpl(
9751 getObjCIdType(), S,
9752 Options.keepingOnly(ObjCEncOptions()
9753 .setExpandPointedToStructures()
9754 .setExpandStructures()),
9755 FD);
9756 if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
9757 // Note that we do extended encoding of protocol qualifier list
9758 // Only when doing ivar or property encoding.
9759 S += '"';
9760 for (const auto *I : OPT->quals()) {
9761 S += '<';
9762 S += I->getObjCRuntimeNameAsString();
9763 S += '>';
9764 }
9765 S += '"';
9766 }
9767 return;
9768 }
9769
9770 S += '@';
9771 if (OPT->getInterfaceDecl() &&
9772 (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
9773 S += '"';
9774 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
9775 for (const auto *I : OPT->quals()) {
9776 S += '<';
9777 S += I->getObjCRuntimeNameAsString();
9778 S += '>';
9779 }
9780 S += '"';
9781 }
9782 return;
9783 }
9784
9785 // gcc just blithely ignores member pointers.
9786 // FIXME: we should do better than that. 'M' is available.
9787 case Type::MemberPointer:
9788 // This matches gcc's encoding, even though technically it is insufficient.
9789 //FIXME. We should do a better job than gcc.
9790 case Type::Vector:
9791 case Type::ExtVector:
9792 // Until we have a coherent encoding of these three types, issue warning.
9793 if (NotEncodedT)
9794 *NotEncodedT = T;
9795 return;
9796
9797 case Type::ConstantMatrix:
9798 if (NotEncodedT)
9799 *NotEncodedT = T;
9800 return;
9801
9802 case Type::BitInt:
9803 if (NotEncodedT)
9804 *NotEncodedT = T;
9805 return;
9806
9807 // We could see an undeduced auto type here during error recovery.
9808 // Just ignore it.
9809 case Type::Auto:
9810 case Type::DeducedTemplateSpecialization:
9811 return;
9812
9813 // An overflow behavior type has the representation of its underlying type.
9814 case Type::OverflowBehavior:
9815 getObjCEncodingForTypeImpl(
9816 cast<OverflowBehaviorType>(CT)->getUnderlyingType(), S, Options, FD,
9817 NotEncodedT);
9818 return;
9819
9820 case Type::HLSLAttributedResource:
9821 case Type::HLSLInlineSpirv:
9822 llvm_unreachable("unexpected type");
9823
9824 case Type::ArrayParameter:
9825 case Type::Pipe:
9826#define ABSTRACT_TYPE(KIND, BASE)
9827#define TYPE(KIND, BASE)
9828#define DEPENDENT_TYPE(KIND, BASE) \
9829 case Type::KIND:
9830#define NON_CANONICAL_TYPE(KIND, BASE) \
9831 case Type::KIND:
9832#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
9833 case Type::KIND:
9834#include "clang/AST/TypeNodes.inc"
9835 llvm_unreachable("@encode for dependent type!");
9836 }
9837 llvm_unreachable("bad type kind!");
9838}
9839
9840void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
9841 std::string &S,
9842 const FieldDecl *FD,
9843 bool includeVBases,
9844 QualType *NotEncodedT) const {
9845 assert(RDecl && "Expected non-null RecordDecl");
9846 assert(!RDecl->isUnion() && "Should not be called for unions");
9847 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
9848 return;
9849
9850 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
9851 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
9852 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
9853
9854 if (CXXRec) {
9855 for (const auto &BI : CXXRec->bases()) {
9856 if (!BI.isVirtual()) {
9857 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9858 if (base->isEmpty())
9859 continue;
9860 uint64_t offs = toBits(layout.getBaseClassOffset(base));
9861 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9862 std::make_pair(offs, base));
9863 }
9864 }
9865 }
9866
9867 for (FieldDecl *Field : RDecl->fields()) {
9868 if (!Field->isZeroLengthBitField() && Field->isZeroSize(*this))
9869 continue;
9870 uint64_t offs = layout.getFieldOffset(Field->getFieldIndex());
9871 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9872 std::make_pair(offs, Field));
9873 }
9874
9875 if (CXXRec && includeVBases) {
9876 for (const auto &BI : CXXRec->vbases()) {
9877 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9878 if (base->isEmpty())
9879 continue;
9880 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
9881 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
9882 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
9883 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
9884 std::make_pair(offs, base));
9885 }
9886 }
9887
9888 CharUnits size;
9889 if (CXXRec) {
9890 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
9891 } else {
9892 size = layout.getSize();
9893 }
9894
9895#ifndef NDEBUG
9896 uint64_t CurOffs = 0;
9897#endif
9898 std::multimap<uint64_t, NamedDecl *>::iterator
9899 CurLayObj = FieldOrBaseOffsets.begin();
9900
9901 if (CXXRec && CXXRec->isDynamicClass() &&
9902 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
9903 if (FD) {
9904 S += "\"_vptr$";
9905 std::string recname = CXXRec->getNameAsString();
9906 if (recname.empty()) recname = "?";
9907 S += recname;
9908 S += '"';
9909 }
9910 S += "^^?";
9911#ifndef NDEBUG
9912 CurOffs += getTypeSize(VoidPtrTy);
9913#endif
9914 }
9915
9916 if (!RDecl->hasFlexibleArrayMember()) {
9917 // Mark the end of the structure.
9918 uint64_t offs = toBits(size);
9919 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9920 std::make_pair(offs, nullptr));
9921 }
9922
9923 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
9924#ifndef NDEBUG
9925 assert(CurOffs <= CurLayObj->first);
9926 if (CurOffs < CurLayObj->first) {
9927 uint64_t padding = CurLayObj->first - CurOffs;
9928 // FIXME: There doesn't seem to be a way to indicate in the encoding that
9929 // packing/alignment of members is different that normal, in which case
9930 // the encoding will be out-of-sync with the real layout.
9931 // If the runtime switches to just consider the size of types without
9932 // taking into account alignment, we could make padding explicit in the
9933 // encoding (e.g. using arrays of chars). The encoding strings would be
9934 // longer then though.
9935 CurOffs += padding;
9936 }
9937#endif
9938
9939 NamedDecl *dcl = CurLayObj->second;
9940 if (!dcl)
9941 break; // reached end of structure.
9942
9943 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
9944 // We expand the bases without their virtual bases since those are going
9945 // in the initial structure. Note that this differs from gcc which
9946 // expands virtual bases each time one is encountered in the hierarchy,
9947 // making the encoding type bigger than it really is.
9948 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
9949 NotEncodedT);
9950 assert(!base->isEmpty());
9951#ifndef NDEBUG
9952 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
9953#endif
9954 } else {
9955 const auto *field = cast<FieldDecl>(dcl);
9956 if (FD) {
9957 S += '"';
9958 S += field->getNameAsString();
9959 S += '"';
9960 }
9961
9962 if (field->isBitField()) {
9963 EncodeBitField(this, S, field->getType(), field);
9964#ifndef NDEBUG
9965 CurOffs += field->getBitWidthValue();
9966#endif
9967 } else {
9968 QualType qt = field->getType();
9970 getObjCEncodingForTypeImpl(
9971 qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(),
9972 FD, NotEncodedT);
9973#ifndef NDEBUG
9974 CurOffs += getTypeSize(field->getType());
9975#endif
9976 }
9977 }
9978 }
9979}
9980
9982 std::string& S) const {
9983 if (QT & Decl::OBJC_TQ_In)
9984 S += 'n';
9985 if (QT & Decl::OBJC_TQ_Inout)
9986 S += 'N';
9987 if (QT & Decl::OBJC_TQ_Out)
9988 S += 'o';
9989 if (QT & Decl::OBJC_TQ_Bycopy)
9990 S += 'O';
9991 if (QT & Decl::OBJC_TQ_Byref)
9992 S += 'R';
9993 if (QT & Decl::OBJC_TQ_Oneway)
9994 S += 'V';
9995}
9996
9998 if (!ObjCIdDecl) {
10001 ObjCIdDecl = buildImplicitTypedef(T, "id");
10002 }
10003 return ObjCIdDecl;
10004}
10005
10007 if (!ObjCSelDecl) {
10009 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
10010 }
10011 return ObjCSelDecl;
10012}
10013
10015 if (!ObjCClassDecl) {
10018 ObjCClassDecl = buildImplicitTypedef(T, "Class");
10019 }
10020 return ObjCClassDecl;
10021}
10022
10024 if (!ObjCProtocolClassDecl) {
10025 ObjCProtocolClassDecl
10028 &Idents.get("Protocol"),
10029 /*typeParamList=*/nullptr,
10030 /*PrevDecl=*/nullptr,
10031 SourceLocation(), true);
10032 }
10033
10034 return ObjCProtocolClassDecl;
10035}
10036
10038 if (!getLangOpts().PointerAuthObjcInterfaceSel)
10039 return PointerAuthQualifier();
10041 getLangOpts().PointerAuthObjcInterfaceSelKey,
10042 /*isAddressDiscriminated=*/true, SelPointerConstantDiscriminator,
10044 /*isIsaPointer=*/false,
10045 /*authenticatesNullValues=*/false);
10046}
10047
10048//===----------------------------------------------------------------------===//
10049// __builtin_va_list Construction Functions
10050//===----------------------------------------------------------------------===//
10051
10053 StringRef Name) {
10054 // typedef char* __builtin[_ms]_va_list;
10055 QualType T = Context->getPointerType(Context->CharTy);
10056 return Context->buildImplicitTypedef(T, Name);
10057}
10058
10060 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
10061}
10062
10064 // typedef char *__builtin_zos_va_list[2];
10065 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 2);
10066 QualType T = Context->getPointerType(Context->CharTy);
10067 QualType ArrayType = Context->getConstantArrayType(
10068 T, Size, nullptr, ArraySizeModifier::Normal, 0);
10069 return Context->buildImplicitTypedef(ArrayType, "__builtin_zos_va_list");
10070}
10071
10073 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
10074}
10075
10077 // typedef void* __builtin_va_list;
10078 QualType T = Context->getPointerType(Context->VoidTy);
10079 return Context->buildImplicitTypedef(T, "__builtin_va_list");
10080}
10081
10082static TypedefDecl *
10084 // struct __va_list
10085 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
10086 if (Context->getLangOpts().CPlusPlus) {
10087 // namespace std { struct __va_list {
10088 auto *NS = NamespaceDecl::Create(
10089 const_cast<ASTContext &>(*Context), Context->getTranslationUnitDecl(),
10090 /*Inline=*/false, SourceLocation(), SourceLocation(),
10091 &Context->Idents.get("std"),
10092 /*PrevDecl=*/nullptr, /*Nested=*/false);
10093 NS->setImplicit();
10095 }
10096
10097 VaListTagDecl->startDefinition();
10098
10099 const size_t NumFields = 5;
10100 QualType FieldTypes[NumFields];
10101 const char *FieldNames[NumFields];
10102
10103 // void *__stack;
10104 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
10105 FieldNames[0] = "__stack";
10106
10107 // void *__gr_top;
10108 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
10109 FieldNames[1] = "__gr_top";
10110
10111 // void *__vr_top;
10112 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10113 FieldNames[2] = "__vr_top";
10114
10115 // int __gr_offs;
10116 FieldTypes[3] = Context->IntTy;
10117 FieldNames[3] = "__gr_offs";
10118
10119 // int __vr_offs;
10120 FieldTypes[4] = Context->IntTy;
10121 FieldNames[4] = "__vr_offs";
10122
10123 // Create fields
10124 for (unsigned i = 0; i < NumFields; ++i) {
10125 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10129 &Context->Idents.get(FieldNames[i]),
10130 FieldTypes[i], /*TInfo=*/nullptr,
10131 /*BitWidth=*/nullptr,
10132 /*Mutable=*/false,
10133 ICIS_NoInit);
10134 Field->setAccess(AS_public);
10135 VaListTagDecl->addDecl(Field);
10136 }
10137 VaListTagDecl->completeDefinition();
10138 Context->VaListTagDecl = VaListTagDecl;
10139 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10140
10141 // } __builtin_va_list;
10142 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
10143}
10144
10146 // typedef struct __va_list_tag {
10148
10149 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10150 VaListTagDecl->startDefinition();
10151
10152 const size_t NumFields = 5;
10153 QualType FieldTypes[NumFields];
10154 const char *FieldNames[NumFields];
10155
10156 // unsigned char gpr;
10157 FieldTypes[0] = Context->UnsignedCharTy;
10158 FieldNames[0] = "gpr";
10159
10160 // unsigned char fpr;
10161 FieldTypes[1] = Context->UnsignedCharTy;
10162 FieldNames[1] = "fpr";
10163
10164 // unsigned short reserved;
10165 FieldTypes[2] = Context->UnsignedShortTy;
10166 FieldNames[2] = "reserved";
10167
10168 // void* overflow_arg_area;
10169 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
10170 FieldNames[3] = "overflow_arg_area";
10171
10172 // void* reg_save_area;
10173 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
10174 FieldNames[4] = "reg_save_area";
10175
10176 // Create fields
10177 for (unsigned i = 0; i < NumFields; ++i) {
10178 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
10181 &Context->Idents.get(FieldNames[i]),
10182 FieldTypes[i], /*TInfo=*/nullptr,
10183 /*BitWidth=*/nullptr,
10184 /*Mutable=*/false,
10185 ICIS_NoInit);
10186 Field->setAccess(AS_public);
10187 VaListTagDecl->addDecl(Field);
10188 }
10189 VaListTagDecl->completeDefinition();
10190 Context->VaListTagDecl = VaListTagDecl;
10191 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10192
10193 // } __va_list_tag;
10194 TypedefDecl *VaListTagTypedefDecl =
10195 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
10196
10197 QualType VaListTagTypedefType =
10198 Context->getTypedefType(ElaboratedTypeKeyword::None,
10199 /*Qualifier=*/std::nullopt, VaListTagTypedefDecl);
10200
10201 // typedef __va_list_tag __builtin_va_list[1];
10202 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10203 QualType VaListTagArrayType = Context->getConstantArrayType(
10204 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
10205 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10206}
10207
10208static TypedefDecl *
10210 // struct __va_list_tag {
10212 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10213 VaListTagDecl->startDefinition();
10214
10215 const size_t NumFields = 4;
10216 QualType FieldTypes[NumFields];
10217 const char *FieldNames[NumFields];
10218
10219 // unsigned gp_offset;
10220 FieldTypes[0] = Context->UnsignedIntTy;
10221 FieldNames[0] = "gp_offset";
10222
10223 // unsigned fp_offset;
10224 FieldTypes[1] = Context->UnsignedIntTy;
10225 FieldNames[1] = "fp_offset";
10226
10227 // void* overflow_arg_area;
10228 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10229 FieldNames[2] = "overflow_arg_area";
10230
10231 // void* reg_save_area;
10232 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
10233 FieldNames[3] = "reg_save_area";
10234
10235 // Create fields
10236 for (unsigned i = 0; i < NumFields; ++i) {
10237 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10241 &Context->Idents.get(FieldNames[i]),
10242 FieldTypes[i], /*TInfo=*/nullptr,
10243 /*BitWidth=*/nullptr,
10244 /*Mutable=*/false,
10245 ICIS_NoInit);
10246 Field->setAccess(AS_public);
10247 VaListTagDecl->addDecl(Field);
10248 }
10249 VaListTagDecl->completeDefinition();
10250 Context->VaListTagDecl = VaListTagDecl;
10251 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10252
10253 // };
10254
10255 // typedef struct __va_list_tag __builtin_va_list[1];
10256 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10257 QualType VaListTagArrayType = Context->getConstantArrayType(
10258 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
10259 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10260}
10261
10262static TypedefDecl *
10264 // struct __va_list
10265 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
10266 if (Context->getLangOpts().CPlusPlus) {
10267 // namespace std { struct __va_list {
10268 NamespaceDecl *NS;
10269 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
10270 Context->getTranslationUnitDecl(),
10271 /*Inline=*/false, SourceLocation(),
10272 SourceLocation(), &Context->Idents.get("std"),
10273 /*PrevDecl=*/nullptr, /*Nested=*/false);
10274 NS->setImplicit();
10275 VaListDecl->setDeclContext(NS);
10276 }
10277
10278 VaListDecl->startDefinition();
10279
10280 // void * __ap;
10281 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10282 VaListDecl,
10285 &Context->Idents.get("__ap"),
10286 Context->getPointerType(Context->VoidTy),
10287 /*TInfo=*/nullptr,
10288 /*BitWidth=*/nullptr,
10289 /*Mutable=*/false,
10290 ICIS_NoInit);
10291 Field->setAccess(AS_public);
10292 VaListDecl->addDecl(Field);
10293
10294 // };
10295 VaListDecl->completeDefinition();
10296 Context->VaListTagDecl = VaListDecl;
10297
10298 // typedef struct __va_list __builtin_va_list;
10299 CanQualType T = Context->getCanonicalTagType(VaListDecl);
10300 return Context->buildImplicitTypedef(T, "__builtin_va_list");
10301}
10302
10303static TypedefDecl *
10305 // struct __va_list_tag {
10307 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10308 VaListTagDecl->startDefinition();
10309
10310 const size_t NumFields = 4;
10311 QualType FieldTypes[NumFields];
10312 const char *FieldNames[NumFields];
10313
10314 // long __gpr;
10315 FieldTypes[0] = Context->LongTy;
10316 FieldNames[0] = "__gpr";
10317
10318 // long __fpr;
10319 FieldTypes[1] = Context->LongTy;
10320 FieldNames[1] = "__fpr";
10321
10322 // void *__overflow_arg_area;
10323 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10324 FieldNames[2] = "__overflow_arg_area";
10325
10326 // void *__reg_save_area;
10327 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
10328 FieldNames[3] = "__reg_save_area";
10329
10330 // Create fields
10331 for (unsigned i = 0; i < NumFields; ++i) {
10332 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10336 &Context->Idents.get(FieldNames[i]),
10337 FieldTypes[i], /*TInfo=*/nullptr,
10338 /*BitWidth=*/nullptr,
10339 /*Mutable=*/false,
10340 ICIS_NoInit);
10341 Field->setAccess(AS_public);
10342 VaListTagDecl->addDecl(Field);
10343 }
10344 VaListTagDecl->completeDefinition();
10345 Context->VaListTagDecl = VaListTagDecl;
10346 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10347
10348 // };
10349
10350 // typedef __va_list_tag __builtin_va_list[1];
10351 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10352 QualType VaListTagArrayType = Context->getConstantArrayType(
10353 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
10354
10355 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10356}
10357
10359 // typedef struct __va_list_tag {
10361 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10362 VaListTagDecl->startDefinition();
10363
10364 const size_t NumFields = 3;
10365 QualType FieldTypes[NumFields];
10366 const char *FieldNames[NumFields];
10367
10368 // void *CurrentSavedRegisterArea;
10369 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
10370 FieldNames[0] = "__current_saved_reg_area_pointer";
10371
10372 // void *SavedRegAreaEnd;
10373 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
10374 FieldNames[1] = "__saved_reg_area_end_pointer";
10375
10376 // void *OverflowArea;
10377 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10378 FieldNames[2] = "__overflow_area_pointer";
10379
10380 // Create fields
10381 for (unsigned i = 0; i < NumFields; ++i) {
10383 const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(),
10384 SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i],
10385 /*TInfo=*/nullptr,
10386 /*BitWidth=*/nullptr,
10387 /*Mutable=*/false, ICIS_NoInit);
10388 Field->setAccess(AS_public);
10389 VaListTagDecl->addDecl(Field);
10390 }
10391 VaListTagDecl->completeDefinition();
10392 Context->VaListTagDecl = VaListTagDecl;
10393 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10394
10395 // } __va_list_tag;
10396 TypedefDecl *VaListTagTypedefDecl =
10397 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
10398
10399 QualType VaListTagTypedefType =
10400 Context->getTypedefType(ElaboratedTypeKeyword::None,
10401 /*Qualifier=*/std::nullopt, VaListTagTypedefDecl);
10402
10403 // typedef __va_list_tag __builtin_va_list[1];
10404 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10405 QualType VaListTagArrayType = Context->getConstantArrayType(
10406 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
10407
10408 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10409}
10410
10411static TypedefDecl *
10413 // typedef struct __va_list_tag {
10414 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10415
10416 VaListTagDecl->startDefinition();
10417
10418 // int* __va_stk;
10419 // int* __va_reg;
10420 // int __va_ndx;
10421 constexpr size_t NumFields = 3;
10422 QualType FieldTypes[NumFields] = {Context->getPointerType(Context->IntTy),
10423 Context->getPointerType(Context->IntTy),
10424 Context->IntTy};
10425 const char *FieldNames[NumFields] = {"__va_stk", "__va_reg", "__va_ndx"};
10426
10427 // Create fields
10428 for (unsigned i = 0; i < NumFields; ++i) {
10431 &Context->Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
10432 /*BitWidth=*/nullptr,
10433 /*Mutable=*/false, ICIS_NoInit);
10434 Field->setAccess(AS_public);
10435 VaListTagDecl->addDecl(Field);
10436 }
10437 VaListTagDecl->completeDefinition();
10438 Context->VaListTagDecl = VaListTagDecl;
10439 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10440
10441 // } __va_list_tag;
10442 TypedefDecl *VaListTagTypedefDecl =
10443 Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
10444
10445 return VaListTagTypedefDecl;
10446}
10447
10450 switch (Kind) {
10452 return CreateCharPtrBuiltinVaListDecl(Context);
10454 return CreateVoidPtrBuiltinVaListDecl(Context);
10456 return CreateAArch64ABIBuiltinVaListDecl(Context);
10458 return CreatePowerABIBuiltinVaListDecl(Context);
10460 return CreateX86_64ABIBuiltinVaListDecl(Context);
10462 return CreateAAPCSABIBuiltinVaListDecl(Context);
10464 return CreateSystemZBuiltinVaListDecl(Context);
10466 return CreateHexagonBuiltinVaListDecl(Context);
10468 return CreateXtensaABIBuiltinVaListDecl(Context);
10469 }
10470
10471 llvm_unreachable("Unhandled __builtin_va_list type kind");
10472}
10473
10475 if (!BuiltinVaListDecl) {
10476 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
10477 assert(BuiltinVaListDecl->isImplicit());
10478 }
10479
10480 return BuiltinVaListDecl;
10481}
10482
10484 // Force the creation of VaListTagDecl by building the __builtin_va_list
10485 // declaration.
10486 if (!VaListTagDecl)
10487 (void)getBuiltinVaListDecl();
10488
10489 return VaListTagDecl;
10490}
10491
10493 if (!BuiltinMSVaListDecl)
10494 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
10495
10496 return BuiltinMSVaListDecl;
10497}
10498
10500 if (!BuiltinZOSVaListDecl)
10501 BuiltinZOSVaListDecl = CreateZOSVaListDecl(this);
10502
10503 return BuiltinZOSVaListDecl;
10504}
10505
10507 // Allow redecl custom type checking builtin for HLSL.
10508 if (LangOpts.HLSL && FD->getBuiltinID() != Builtin::NotBuiltin &&
10509 BuiltinInfo.hasCustomTypechecking(FD->getBuiltinID()))
10510 return true;
10511 // Allow redecl custom type checking builtin for SPIR-V.
10512 if (getTargetInfo().getTriple().isSPIROrSPIRV() &&
10513 BuiltinInfo.isTSBuiltin(FD->getBuiltinID()) &&
10514 BuiltinInfo.hasCustomTypechecking(FD->getBuiltinID()))
10515 return true;
10516 return BuiltinInfo.canBeRedeclared(FD->getBuiltinID());
10517}
10518
10520 assert(ObjCConstantStringType.isNull() &&
10521 "'NSConstantString' type already set!");
10522
10523 ObjCConstantStringType = getObjCInterfaceType(Decl);
10524}
10525
10526/// Retrieve the template name that corresponds to a non-empty
10527/// lookup.
10530 UnresolvedSetIterator End) const {
10531 unsigned size = End - Begin;
10532 assert(size > 1 && "set is not overloaded!");
10533
10534 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
10535 size * sizeof(FunctionTemplateDecl*));
10536 auto *OT = new (memory) OverloadedTemplateStorage(size);
10537
10538 NamedDecl **Storage = OT->getStorage();
10539 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
10540 NamedDecl *D = *I;
10541 assert(isa<FunctionTemplateDecl>(D) ||
10545 *Storage++ = D;
10546 }
10547
10548 return TemplateName(OT);
10549}
10550
10551/// Retrieve a template name representing an unqualified-id that has been
10552/// assumed to name a template for ADL purposes.
10554 auto *OT = new (*this) AssumedTemplateStorage(Name);
10555 return TemplateName(OT);
10556}
10557
10558/// Retrieve the template name that represents a qualified
10559/// template name such as \c std::vector.
10561 bool TemplateKeyword,
10562 TemplateName Template) const {
10563 assert(Template.getKind() == TemplateName::Template ||
10565
10566 if (Template.getAsTemplateDecl()->getKind() == Decl::TemplateTemplateParm) {
10567 assert(!Qualifier && "unexpected qualified template template parameter");
10568 assert(TemplateKeyword == false);
10569 return Template;
10570 }
10571
10572 // FIXME: Canonicalization?
10573 llvm::FoldingSetNodeID ID;
10574 QualifiedTemplateName::Profile(ID, Qualifier, TemplateKeyword, Template);
10575
10576 llvm::FoldingSetInsertToken Token;
10577 QualifiedTemplateName *QTN = QualifiedTemplateNames.lookup(ID, Token);
10578 if (!QTN) {
10579 QTN = new (*this, alignof(QualifiedTemplateName))
10580 QualifiedTemplateName(Qualifier, TemplateKeyword, Template);
10581 QualifiedTemplateNames.insert(QTN, Token);
10582 }
10583
10584 return TemplateName(QTN);
10585}
10586
10587/// Retrieve the template name that represents a dependent
10588/// template name such as \c MetaFun::template operator+.
10591 llvm::FoldingSetNodeID ID;
10592 S.Profile(ID);
10593
10594 llvm::FoldingSetInsertToken Token;
10595 if (DependentTemplateName *QTN = DependentTemplateNames.lookup(ID, Token))
10596 return TemplateName(QTN);
10597
10599 new (*this, alignof(DependentTemplateName)) DependentTemplateName(S);
10600 DependentTemplateNames.insert(QTN, Token);
10601 return TemplateName(QTN);
10602}
10603
10605 Decl *AssociatedDecl,
10606 unsigned Index,
10608 bool Final) const {
10609 llvm::FoldingSetNodeID ID;
10610 SubstTemplateTemplateParmStorage::Profile(ID, Replacement, AssociatedDecl,
10611 Index, PackIndex, Final);
10612
10613 llvm::FoldingSetInsertToken Token;
10615 SubstTemplateTemplateParms.lookup(ID, Token);
10616
10617 if (!subst) {
10618 subst = new (*this) SubstTemplateTemplateParmStorage(
10619 Replacement, AssociatedDecl, Index, PackIndex, Final);
10620 SubstTemplateTemplateParms.insert(subst, Token);
10621 }
10622
10623 return TemplateName(subst);
10624}
10625
10628 Decl *AssociatedDecl,
10629 unsigned Index, bool Final) const {
10630 auto &Self = const_cast<ASTContext &>(*this);
10631 llvm::FoldingSetNodeID ID;
10633 AssociatedDecl, Index, Final);
10634
10635 llvm::FoldingSetInsertToken Token;
10637 SubstTemplateTemplateParmPacks.lookup(ID, Token);
10638
10639 if (!Subst) {
10640 Subst = new (*this) SubstTemplateTemplateParmPackStorage(
10641 ArgPack.pack_elements(), AssociatedDecl, Index, Final);
10642 SubstTemplateTemplateParmPacks.insert(Subst, Token);
10643 }
10644
10645 return TemplateName(Subst);
10646}
10647
10648/// Retrieve the template name that represents a template name
10649/// deduced from a specialization.
10652 DefaultArguments DefaultArgs) const {
10653 if (!DefaultArgs)
10654 return Underlying;
10655
10656 llvm::FoldingSetNodeID ID;
10657 DeducedTemplateStorage::Profile(ID, *this, Underlying, DefaultArgs);
10658
10659 llvm::FoldingSetInsertToken Token;
10660 DeducedTemplateStorage *DTS = DeducedTemplates.lookup(ID, Token);
10661 if (!DTS) {
10662 void *Mem = Allocate(sizeof(DeducedTemplateStorage) +
10663 sizeof(TemplateArgument) * DefaultArgs.Args.size(),
10664 alignof(DeducedTemplateStorage));
10665 DTS = new (Mem) DeducedTemplateStorage(Underlying, DefaultArgs);
10666 DeducedTemplates.insert(DTS, Token);
10667 }
10668 return TemplateName(DTS);
10669}
10670
10672 TemplateName Pattern, Expr *IndexExpr, bool FullySubstituted,
10673 ArrayRef<TemplateName> Expansions) const {
10674 auto &Self = const_cast<ASTContext &>(*this);
10675 llvm::FoldingSetNodeID ID;
10676 PackIndexingTemplateStorage::Profile(ID, Self, Pattern, IndexExpr,
10677 FullySubstituted, Expansions);
10678
10679 llvm::FoldingSetInsertToken Token;
10680 PackIndexingTemplateStorage *PI = PackIndexingTemplates.lookup(ID, Token);
10681 if (!PI) {
10682 void *Mem =
10683 Allocate(PackIndexingTemplateStorage::totalSizeToAlloc<TemplateName>(
10684 Expansions.size()),
10686 PI = new (Mem) PackIndexingTemplateStorage(Pattern, IndexExpr,
10687 FullySubstituted, Expansions);
10688 PackIndexingTemplates.insert(PI, Token);
10689 }
10690 return TemplateName(PI);
10691}
10692
10693/// getFromTargetType - Given one of the integer types provided by
10694/// TargetInfo, produce the corresponding type. The unsigned @p Type
10695/// is actually a value of type @c TargetInfo::IntType.
10696CanQualType ASTContext::getFromTargetType(unsigned Type) const {
10697 switch (Type) {
10698 case TargetInfo::NoInt: return {};
10701 case TargetInfo::SignedShort: return ShortTy;
10703 case TargetInfo::SignedInt: return IntTy;
10705 case TargetInfo::SignedLong: return LongTy;
10709 }
10710
10711 llvm_unreachable("Unhandled TargetInfo::IntType value");
10712}
10713
10714//===----------------------------------------------------------------------===//
10715// Type Predicates.
10716//===----------------------------------------------------------------------===//
10717
10718/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
10719/// garbage collection attribute.
10720///
10722 if (getLangOpts().getGC() == LangOptions::NonGC)
10723 return Qualifiers::GCNone;
10724
10725 assert(getLangOpts().ObjC);
10726 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
10727
10728 // Default behaviour under objective-C's gc is for ObjC pointers
10729 // (or pointers to them) be treated as though they were declared
10730 // as __strong.
10731 if (GCAttrs == Qualifiers::GCNone) {
10733 return Qualifiers::Strong;
10734 else if (Ty->isPointerType())
10736 } else {
10737 // It's not valid to set GC attributes on anything that isn't a
10738 // pointer.
10739#ifndef NDEBUG
10741 while (const auto *AT = dyn_cast<ArrayType>(CT))
10742 CT = AT->getElementType();
10743 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
10744#endif
10745 }
10746 return GCAttrs;
10747}
10748
10749//===----------------------------------------------------------------------===//
10750// Type Compatibility Testing
10751//===----------------------------------------------------------------------===//
10752
10753/// areCompatVectorTypes - Return true if the two specified vector types are
10754/// compatible.
10755static bool areCompatVectorTypes(const VectorType *LHS,
10756 const VectorType *RHS) {
10757 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10758 return LHS->getElementType() == RHS->getElementType() &&
10759 LHS->getNumElements() == RHS->getNumElements();
10760}
10761
10762/// areCompatMatrixTypes - Return true if the two specified matrix types are
10763/// compatible.
10765 const ConstantMatrixType *RHS) {
10766 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10767 return LHS->getElementType() == RHS->getElementType() &&
10768 LHS->getNumRows() == RHS->getNumRows() &&
10769 LHS->getNumColumns() == RHS->getNumColumns();
10770}
10771
10773 QualType SecondVec) {
10774 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
10775 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
10776
10777 if (hasSameUnqualifiedType(FirstVec, SecondVec))
10778 return true;
10779
10780 // Treat Neon vector types and most AltiVec vector types as if they are the
10781 // equivalent GCC vector types.
10782 const auto *First = FirstVec->castAs<VectorType>();
10783 const auto *Second = SecondVec->castAs<VectorType>();
10784 if (First->getNumElements() == Second->getNumElements() &&
10785 hasSameType(First->getElementType(), Second->getElementType()) &&
10786 First->getVectorKind() != VectorKind::AltiVecPixel &&
10787 First->getVectorKind() != VectorKind::AltiVecBool &&
10790 First->getVectorKind() != VectorKind::SveFixedLengthData &&
10791 First->getVectorKind() != VectorKind::SveFixedLengthPredicate &&
10794 !isRVVFixedLengthVectorKind(First->getVectorKind()) &&
10796 return true;
10797
10798 // In OpenCL, treat half and _Float16 vector types as compatible.
10799 if (getLangOpts().OpenCL &&
10800 First->getNumElements() == Second->getNumElements()) {
10801 QualType FirstElt = First->getElementType();
10802 QualType SecondElt = Second->getElementType();
10803
10804 if ((FirstElt->isFloat16Type() && SecondElt->isHalfType()) ||
10805 (FirstElt->isHalfType() && SecondElt->isFloat16Type())) {
10806 if (First->getVectorKind() != VectorKind::AltiVecPixel &&
10807 First->getVectorKind() != VectorKind::AltiVecBool &&
10810 return true;
10811 }
10812 }
10813 return false;
10814}
10815
10821
10824 const auto *LHSOBT = LHS->getAs<OverflowBehaviorType>();
10825 const auto *RHSOBT = RHS->getAs<OverflowBehaviorType>();
10826
10827 if (!LHSOBT && !RHSOBT)
10829
10830 if (LHSOBT && RHSOBT) {
10831 if (LHSOBT->getBehaviorKind() != RHSOBT->getBehaviorKind())
10834 }
10835
10836 QualType LHSUnderlying = LHSOBT ? LHSOBT->desugar() : LHS;
10837 QualType RHSUnderlying = RHSOBT ? RHSOBT->desugar() : RHS;
10838
10839 if (RHSOBT && !LHSOBT) {
10840 if (LHSUnderlying->isIntegerType() && RHSUnderlying->isIntegerType())
10842 }
10843
10845}
10846
10847/// getRVVTypeSize - Return RVV vector register size.
10848static uint64_t getRVVTypeSize(ASTContext &Context, const BuiltinType *Ty) {
10849 assert(Ty->isRVVVLSBuiltinType() && "Invalid RVV Type");
10850 auto VScale = Context.getTargetInfo().getVScaleRange(
10851 Context.getLangOpts(), TargetInfo::ArmStreamingKind::NotStreaming);
10852 if (!VScale)
10853 return 0;
10854
10855 ASTContext::BuiltinVectorTypeInfo Info = Context.getBuiltinVectorTypeInfo(Ty);
10856
10857 uint64_t EltSize = Context.getTypeSize(Info.ElementType);
10858 if (Info.ElementType == Context.BoolTy)
10859 EltSize = 1;
10860
10861 uint64_t MinElts = Info.EC.getKnownMinValue();
10862 return VScale->first * MinElts * EltSize;
10863}
10864
10866 QualType SecondType) {
10867 assert(
10868 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10869 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10870 "Expected RVV builtin type and vector type!");
10871
10872 auto IsValidCast = [this](QualType FirstType, QualType SecondType) {
10873 if (const auto *BT = FirstType->getAs<BuiltinType>()) {
10874 if (const auto *VT = SecondType->getAs<VectorType>()) {
10875 if (isRVVFixedLengthMaskVectorKind(VT->getVectorKind())) {
10877 // A mask typedef converts to and from the vbool<R>_t type it was
10878 // written against: vbool<R>_t has RVVBitsPerBlock / R lanes at
10879 // vscale=1.
10880 return FirstType->isRVVVLSBuiltinType() &&
10881 Info.ElementType == BoolTy &&
10882 (llvm::RISCV::RVVBitsPerBlock >>
10883 getRVVFixedLengthMaskRatioLog2(VT->getVectorKind())) ==
10884 Info.EC.getKnownMinValue() &&
10885 VT->getRVVFixedLengthMaskLanes() == getRVVTypeSize(*this, BT);
10886 }
10887 if (isRVVFixedLengthDataVectorKind(VT->getVectorKind()) ||
10888 VT->getVectorKind() == VectorKind::Generic)
10889 return FirstType->isRVVVLSBuiltinType() &&
10890 getTypeSize(SecondType) == getRVVTypeSize(*this, BT) &&
10891 hasSameType(VT->getElementType(),
10892 getBuiltinVectorTypeInfo(BT).ElementType);
10893 }
10894 }
10895 return false;
10896 };
10897
10898 return IsValidCast(FirstType, SecondType) ||
10899 IsValidCast(SecondType, FirstType);
10900}
10901
10903 QualType SecondType) {
10904 assert(
10905 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10906 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10907 "Expected RVV builtin type and vector type!");
10908
10909 auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) {
10910 const auto *BT = FirstType->getAs<BuiltinType>();
10911 if (!BT)
10912 return false;
10913
10914 if (!BT->isRVVVLSBuiltinType())
10915 return false;
10916
10917 const auto *VecTy = SecondType->getAs<VectorType>();
10918 if (VecTy && VecTy->getVectorKind() == VectorKind::Generic) {
10920 getLangOpts().getLaxVectorConversions();
10921
10922 // If __riscv_v_fixed_vlen != N do not allow vector lax conversion.
10923 if (getTypeSize(SecondType) != getRVVTypeSize(*this, BT))
10924 return false;
10925
10926 // If -flax-vector-conversions=all is specified, the types are
10927 // certainly compatible.
10929 return true;
10930
10931 // If -flax-vector-conversions=integer is specified, the types are
10932 // compatible if the elements are integer types.
10934 return VecTy->getElementType().getCanonicalType()->isIntegerType() &&
10935 FirstType->getRVVEltType(*this)->isIntegerType();
10936 }
10937
10938 return false;
10939 };
10940
10941 return IsLaxCompatible(FirstType, SecondType) ||
10942 IsLaxCompatible(SecondType, FirstType);
10943}
10944
10946 while (true) {
10947 // __strong id
10948 if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) {
10949 if (Attr->getAttrKind() == attr::ObjCOwnership)
10950 return true;
10951
10952 Ty = Attr->getModifiedType();
10953
10954 // X *__strong (...)
10955 } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) {
10956 Ty = Paren->getInnerType();
10957
10958 // We do not want to look through typedefs, typeof(expr),
10959 // typeof(type), or any other way that the type is somehow
10960 // abstracted.
10961 } else {
10962 return false;
10963 }
10964 }
10965}
10966
10967//===----------------------------------------------------------------------===//
10968// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
10969//===----------------------------------------------------------------------===//
10970
10971/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
10972/// inheritance hierarchy of 'rProto'.
10973bool
10975 ObjCProtocolDecl *rProto) const {
10976 if (declaresSameEntity(lProto, rProto))
10977 return true;
10978 for (auto *PI : rProto->protocols())
10979 if (ProtocolCompatibleWithProtocol(lProto, PI))
10980 return true;
10981 return false;
10982}
10983
10984/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
10985/// Class<pr1, ...>.
10987 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) {
10988 for (auto *lhsProto : lhs->quals()) {
10989 bool match = false;
10990 for (auto *rhsProto : rhs->quals()) {
10991 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
10992 match = true;
10993 break;
10994 }
10995 }
10996 if (!match)
10997 return false;
10998 }
10999 return true;
11000}
11001
11002/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
11003/// ObjCQualifiedIDType.
11005 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs,
11006 bool compare) {
11007 // Allow id<P..> and an 'id' in all cases.
11008 if (lhs->isObjCIdType() || rhs->isObjCIdType())
11009 return true;
11010
11011 // Don't allow id<P..> to convert to Class or Class<P..> in either direction.
11012 if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() ||
11014 return false;
11015
11016 if (lhs->isObjCQualifiedIdType()) {
11017 if (rhs->qual_empty()) {
11018 // If the RHS is a unqualified interface pointer "NSString*",
11019 // make sure we check the class hierarchy.
11020 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
11021 for (auto *I : lhs->quals()) {
11022 // when comparing an id<P> on lhs with a static type on rhs,
11023 // see if static class implements all of id's protocols, directly or
11024 // through its super class and categories.
11025 if (!rhsID->ClassImplementsProtocol(I, true))
11026 return false;
11027 }
11028 }
11029 // If there are no qualifiers and no interface, we have an 'id'.
11030 return true;
11031 }
11032 // Both the right and left sides have qualifiers.
11033 for (auto *lhsProto : lhs->quals()) {
11034 bool match = false;
11035
11036 // when comparing an id<P> on lhs with a static type on rhs,
11037 // see if static class implements all of id's protocols, directly or
11038 // through its super class and categories.
11039 for (auto *rhsProto : rhs->quals()) {
11040 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
11041 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
11042 match = true;
11043 break;
11044 }
11045 }
11046 // If the RHS is a qualified interface pointer "NSString<P>*",
11047 // make sure we check the class hierarchy.
11048 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
11049 for (auto *I : lhs->quals()) {
11050 // when comparing an id<P> on lhs with a static type on rhs,
11051 // see if static class implements all of id's protocols, directly or
11052 // through its super class and categories.
11053 if (rhsID->ClassImplementsProtocol(I, true)) {
11054 match = true;
11055 break;
11056 }
11057 }
11058 }
11059 if (!match)
11060 return false;
11061 }
11062
11063 return true;
11064 }
11065
11066 assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>");
11067
11068 if (lhs->getInterfaceType()) {
11069 // If both the right and left sides have qualifiers.
11070 for (auto *lhsProto : lhs->quals()) {
11071 bool match = false;
11072
11073 // when comparing an id<P> on rhs with a static type on lhs,
11074 // see if static class implements all of id's protocols, directly or
11075 // through its super class and categories.
11076 // First, lhs protocols in the qualifier list must be found, direct
11077 // or indirect in rhs's qualifier list or it is a mismatch.
11078 for (auto *rhsProto : rhs->quals()) {
11079 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
11080 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
11081 match = true;
11082 break;
11083 }
11084 }
11085 if (!match)
11086 return false;
11087 }
11088
11089 // Static class's protocols, or its super class or category protocols
11090 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
11091 if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) {
11092 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
11093 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
11094 // This is rather dubious but matches gcc's behavior. If lhs has
11095 // no type qualifier and its class has no static protocol(s)
11096 // assume that it is mismatch.
11097 if (LHSInheritedProtocols.empty() && lhs->qual_empty())
11098 return false;
11099 for (auto *lhsProto : LHSInheritedProtocols) {
11100 bool match = false;
11101 for (auto *rhsProto : rhs->quals()) {
11102 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
11103 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
11104 match = true;
11105 break;
11106 }
11107 }
11108 if (!match)
11109 return false;
11110 }
11111 }
11112 return true;
11113 }
11114 return false;
11115}
11116
11117/// canAssignObjCInterfaces - Return true if the two interface types are
11118/// compatible for assignment from RHS to LHS. This handles validation of any
11119/// protocol qualifiers on the LHS or RHS.
11121 const ObjCObjectPointerType *RHSOPT) {
11122 const ObjCObjectType* LHS = LHSOPT->getObjectType();
11123 const ObjCObjectType* RHS = RHSOPT->getObjectType();
11124
11125 // If either type represents the built-in 'id' type, return true.
11126 if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId())
11127 return true;
11128
11129 // Function object that propagates a successful result or handles
11130 // __kindof types.
11131 auto finish = [&](bool succeeded) -> bool {
11132 if (succeeded)
11133 return true;
11134
11135 if (!RHS->isKindOfType())
11136 return false;
11137
11138 // Strip off __kindof and protocol qualifiers, then check whether
11139 // we can assign the other way.
11141 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
11142 };
11143
11144 // Casts from or to id<P> are allowed when the other side has compatible
11145 // protocols.
11146 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
11147 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false));
11148 }
11149
11150 // Verify protocol compatibility for casts from Class<P1> to Class<P2>.
11151 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
11152 return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT));
11153 }
11154
11155 // Casts from Class to Class<Foo>, or vice-versa, are allowed.
11156 if (LHS->isObjCClass() && RHS->isObjCClass()) {
11157 return true;
11158 }
11159
11160 // If we have 2 user-defined types, fall into that path.
11161 if (LHS->getInterface() && RHS->getInterface()) {
11162 return finish(canAssignObjCInterfaces(LHS, RHS));
11163 }
11164
11165 return false;
11166}
11167
11168/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
11169/// for providing type-safety for objective-c pointers used to pass/return
11170/// arguments in block literals. When passed as arguments, passing 'A*' where
11171/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
11172/// not OK. For the return type, the opposite is not OK.
11174 const ObjCObjectPointerType *LHSOPT,
11175 const ObjCObjectPointerType *RHSOPT,
11176 bool BlockReturnType) {
11177
11178 // Function object that propagates a successful result or handles
11179 // __kindof types.
11180 auto finish = [&](bool succeeded) -> bool {
11181 if (succeeded)
11182 return true;
11183
11184 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
11185 if (!Expected->isKindOfType())
11186 return false;
11187
11188 // Strip off __kindof and protocol qualifiers, then check whether
11189 // we can assign the other way.
11191 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
11192 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
11193 BlockReturnType);
11194 };
11195
11196 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
11197 return true;
11198
11199 if (LHSOPT->isObjCBuiltinType()) {
11200 return finish(RHSOPT->isObjCBuiltinType() ||
11201 RHSOPT->isObjCQualifiedIdType());
11202 }
11203
11204 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) {
11205 if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking)
11206 // Use for block parameters previous type checking for compatibility.
11207 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false) ||
11208 // Or corrected type checking as in non-compat mode.
11209 (!BlockReturnType &&
11210 ObjCQualifiedIdTypesAreCompatible(RHSOPT, LHSOPT, false)));
11211 else
11213 (BlockReturnType ? LHSOPT : RHSOPT),
11214 (BlockReturnType ? RHSOPT : LHSOPT), false));
11215 }
11216
11217 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
11218 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
11219 if (LHS && RHS) { // We have 2 user-defined types.
11220 if (LHS != RHS) {
11221 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
11222 return finish(BlockReturnType);
11223 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
11224 return finish(!BlockReturnType);
11225 }
11226 else
11227 return true;
11228 }
11229 return false;
11230}
11231
11232/// Comparison routine for Objective-C protocols to be used with
11233/// llvm::array_pod_sort.
11235 ObjCProtocolDecl * const *rhs) {
11236 return (*lhs)->getName().compare((*rhs)->getName());
11237}
11238
11239/// getIntersectionOfProtocols - This routine finds the intersection of set
11240/// of protocols inherited from two distinct objective-c pointer objects with
11241/// the given common base.
11242/// It is used to build composite qualifier list of the composite type of
11243/// the conditional expression involving two objective-c pointer objects.
11244static
11246 const ObjCInterfaceDecl *CommonBase,
11247 const ObjCObjectPointerType *LHSOPT,
11248 const ObjCObjectPointerType *RHSOPT,
11249 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
11250
11251 const ObjCObjectType* LHS = LHSOPT->getObjectType();
11252 const ObjCObjectType* RHS = RHSOPT->getObjectType();
11253 assert(LHS->getInterface() && "LHS must have an interface base");
11254 assert(RHS->getInterface() && "RHS must have an interface base");
11255
11256 // Add all of the protocols for the LHS.
11258
11259 // Start with the protocol qualifiers.
11260 for (auto *proto : LHS->quals()) {
11261 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
11262 }
11263
11264 // Also add the protocols associated with the LHS interface.
11265 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
11266
11267 // Add all of the protocols for the RHS.
11269
11270 // Start with the protocol qualifiers.
11271 for (auto *proto : RHS->quals()) {
11272 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
11273 }
11274
11275 // Also add the protocols associated with the RHS interface.
11276 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
11277
11278 // Compute the intersection of the collected protocol sets.
11279 for (auto *proto : LHSProtocolSet) {
11280 if (RHSProtocolSet.count(proto))
11281 IntersectionSet.push_back(proto);
11282 }
11283
11284 // Compute the set of protocols that is implied by either the common type or
11285 // the protocols within the intersection.
11287 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
11288
11289 // Remove any implied protocols from the list of inherited protocols.
11290 if (!ImpliedProtocols.empty()) {
11291 llvm::erase_if(IntersectionSet, [&](ObjCProtocolDecl *proto) -> bool {
11292 return ImpliedProtocols.contains(proto);
11293 });
11294 }
11295
11296 // Sort the remaining protocols by name.
11297 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
11299}
11300
11301/// Determine whether the first type is a subtype of the second.
11303 QualType rhs) {
11304 // Common case: two object pointers.
11305 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
11306 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
11307 if (lhsOPT && rhsOPT)
11308 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
11309
11310 // Two block pointers.
11311 const auto *lhsBlock = lhs->getAs<BlockPointerType>();
11312 const auto *rhsBlock = rhs->getAs<BlockPointerType>();
11313 if (lhsBlock && rhsBlock)
11314 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
11315
11316 // If either is an unqualified 'id' and the other is a block, it's
11317 // acceptable.
11318 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
11319 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
11320 return true;
11321
11322 return false;
11323}
11324
11325// Check that the given Objective-C type argument lists are equivalent.
11327 const ObjCInterfaceDecl *iface,
11328 ArrayRef<QualType> lhsArgs,
11329 ArrayRef<QualType> rhsArgs,
11330 bool stripKindOf) {
11331 if (lhsArgs.size() != rhsArgs.size())
11332 return false;
11333
11334 ObjCTypeParamList *typeParams = iface->getTypeParamList();
11335 if (!typeParams)
11336 return false;
11337
11338 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
11339 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
11340 continue;
11341
11342 switch (typeParams->begin()[i]->getVariance()) {
11344 if (!stripKindOf ||
11345 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
11346 rhsArgs[i].stripObjCKindOfType(ctx))) {
11347 return false;
11348 }
11349 break;
11350
11352 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
11353 return false;
11354 break;
11355
11357 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
11358 return false;
11359 break;
11360 }
11361 }
11362
11363 return true;
11364}
11365
11367 const ObjCObjectPointerType *Lptr,
11368 const ObjCObjectPointerType *Rptr) {
11369 const ObjCObjectType *LHS = Lptr->getObjectType();
11370 const ObjCObjectType *RHS = Rptr->getObjectType();
11371 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
11372 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
11373
11374 if (!LDecl || !RDecl)
11375 return {};
11376
11377 // When either LHS or RHS is a kindof type, we should return a kindof type.
11378 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
11379 // kindof(A).
11380 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
11381
11382 // Follow the left-hand side up the class hierarchy until we either hit a
11383 // root or find the RHS. Record the ancestors in case we don't find it.
11384 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
11385 LHSAncestors;
11386 while (true) {
11387 // Record this ancestor. We'll need this if the common type isn't in the
11388 // path from the LHS to the root.
11389 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
11390
11391 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
11392 // Get the type arguments.
11393 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
11394 bool anyChanges = false;
11395 if (LHS->isSpecialized() && RHS->isSpecialized()) {
11396 // Both have type arguments, compare them.
11397 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
11398 LHS->getTypeArgs(), RHS->getTypeArgs(),
11399 /*stripKindOf=*/true))
11400 return {};
11401 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
11402 // If only one has type arguments, the result will not have type
11403 // arguments.
11404 LHSTypeArgs = {};
11405 anyChanges = true;
11406 }
11407
11408 // Compute the intersection of protocols.
11410 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
11411 Protocols);
11412 if (!Protocols.empty())
11413 anyChanges = true;
11414
11415 // If anything in the LHS will have changed, build a new result type.
11416 // If we need to return a kindof type but LHS is not a kindof type, we
11417 // build a new result type.
11418 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
11419 QualType Result = getObjCInterfaceType(LHS->getInterface());
11420 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
11421 anyKindOf || LHS->isKindOfType());
11423 }
11424
11425 return getObjCObjectPointerType(QualType(LHS, 0));
11426 }
11427
11428 // Find the superclass.
11429 QualType LHSSuperType = LHS->getSuperClassType();
11430 if (LHSSuperType.isNull())
11431 break;
11432
11433 LHS = LHSSuperType->castAs<ObjCObjectType>();
11434 }
11435
11436 // We didn't find anything by following the LHS to its root; now check
11437 // the RHS against the cached set of ancestors.
11438 while (true) {
11439 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
11440 if (KnownLHS != LHSAncestors.end()) {
11441 LHS = KnownLHS->second;
11442
11443 // Get the type arguments.
11444 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
11445 bool anyChanges = false;
11446 if (LHS->isSpecialized() && RHS->isSpecialized()) {
11447 // Both have type arguments, compare them.
11448 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
11449 LHS->getTypeArgs(), RHS->getTypeArgs(),
11450 /*stripKindOf=*/true))
11451 return {};
11452 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
11453 // If only one has type arguments, the result will not have type
11454 // arguments.
11455 RHSTypeArgs = {};
11456 anyChanges = true;
11457 }
11458
11459 // Compute the intersection of protocols.
11461 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
11462 Protocols);
11463 if (!Protocols.empty())
11464 anyChanges = true;
11465
11466 // If we need to return a kindof type but RHS is not a kindof type, we
11467 // build a new result type.
11468 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
11469 QualType Result = getObjCInterfaceType(RHS->getInterface());
11470 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
11471 anyKindOf || RHS->isKindOfType());
11473 }
11474
11475 return getObjCObjectPointerType(QualType(RHS, 0));
11476 }
11477
11478 // Find the superclass of the RHS.
11479 QualType RHSSuperType = RHS->getSuperClassType();
11480 if (RHSSuperType.isNull())
11481 break;
11482
11483 RHS = RHSSuperType->castAs<ObjCObjectType>();
11484 }
11485
11486 return {};
11487}
11488
11490 const ObjCObjectType *RHS) {
11491 assert(LHS->getInterface() && "LHS is not an interface type");
11492 assert(RHS->getInterface() && "RHS is not an interface type");
11493
11494 // Verify that the base decls are compatible: the RHS must be a subclass of
11495 // the LHS.
11496 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
11497 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
11498 if (!IsSuperClass)
11499 return false;
11500
11501 // If the LHS has protocol qualifiers, determine whether all of them are
11502 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
11503 // LHS).
11504 if (LHS->getNumProtocols() > 0) {
11505 // OK if conversion of LHS to SuperClass results in narrowing of types
11506 // ; i.e., SuperClass may implement at least one of the protocols
11507 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
11508 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
11509 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
11510 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
11511 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
11512 // qualifiers.
11513 for (auto *RHSPI : RHS->quals())
11514 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
11515 // If there is no protocols associated with RHS, it is not a match.
11516 if (SuperClassInheritedProtocols.empty())
11517 return false;
11518
11519 for (const auto *LHSProto : LHS->quals()) {
11520 bool SuperImplementsProtocol = false;
11521 for (auto *SuperClassProto : SuperClassInheritedProtocols)
11522 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
11523 SuperImplementsProtocol = true;
11524 break;
11525 }
11526 if (!SuperImplementsProtocol)
11527 return false;
11528 }
11529 }
11530
11531 // If the LHS is specialized, we may need to check type arguments.
11532 if (LHS->isSpecialized()) {
11533 // Follow the superclass chain until we've matched the LHS class in the
11534 // hierarchy. This substitutes type arguments through.
11535 const ObjCObjectType *RHSSuper = RHS;
11536 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
11537 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
11538
11539 // If the RHS is specializd, compare type arguments.
11540 if (RHSSuper->isSpecialized() &&
11541 !sameObjCTypeArgs(*this, LHS->getInterface(),
11542 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
11543 /*stripKindOf=*/true)) {
11544 return false;
11545 }
11546 }
11547
11548 return true;
11549}
11550
11552 // get the "pointed to" types
11553 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
11554 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
11555
11556 if (!LHSOPT || !RHSOPT)
11557 return false;
11558
11559 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
11560 canAssignObjCInterfaces(RHSOPT, LHSOPT);
11561}
11562
11565 getObjCObjectPointerType(To)->castAs<ObjCObjectPointerType>(),
11566 getObjCObjectPointerType(From)->castAs<ObjCObjectPointerType>());
11567}
11568
11569/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
11570/// both shall have the identically qualified version of a compatible type.
11571/// C99 6.2.7p1: Two types have compatible types if their types are the
11572/// same. See 6.7.[2,3,5] for additional rules.
11574 bool CompareUnqualified) {
11575 if (getLangOpts().CPlusPlus)
11576 return hasSameType(LHS, RHS);
11577
11578 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
11579}
11580
11582 return typesAreCompatible(LHS, RHS);
11583}
11584
11586 return !mergeTypes(LHS, RHS, true).isNull();
11587}
11588
11589/// mergeTransparentUnionType - if T is a transparent union type and a member
11590/// of T is compatible with SubType, return the merged type, else return
11591/// QualType()
11593 bool OfBlockPointer,
11594 bool Unqualified) {
11595 if (const RecordType *UT = T->getAsUnionType()) {
11596 RecordDecl *UD = UT->getDecl()->getMostRecentDecl();
11597 if (UD->hasAttr<TransparentUnionAttr>()) {
11598 for (const auto *I : UD->fields()) {
11599 QualType ET = I->getType().getUnqualifiedType();
11600 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
11601 if (!MT.isNull())
11602 return MT;
11603 }
11604 }
11605 }
11606
11607 return {};
11608}
11609
11610/// mergeFunctionParameterTypes - merge two types which appear as function
11611/// parameter types
11613 bool OfBlockPointer,
11614 bool Unqualified) {
11615 // GNU extension: two types are compatible if they appear as a function
11616 // argument, one of the types is a transparent union type and the other
11617 // type is compatible with a union member
11618 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
11619 Unqualified);
11620 if (!lmerge.isNull())
11621 return lmerge;
11622
11623 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
11624 Unqualified);
11625 if (!rmerge.isNull())
11626 return rmerge;
11627
11628 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
11629}
11630
11632 bool OfBlockPointer, bool Unqualified,
11633 bool AllowCXX,
11634 bool IsConditionalOperator) {
11635 const auto *lbase = lhs->castAs<FunctionType>();
11636 const auto *rbase = rhs->castAs<FunctionType>();
11637 const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
11638 const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
11639 bool allLTypes = true;
11640 bool allRTypes = true;
11641
11642 // Check return type
11643 QualType retType;
11644 if (OfBlockPointer) {
11645 QualType RHS = rbase->getReturnType();
11646 QualType LHS = lbase->getReturnType();
11647 bool UnqualifiedResult = Unqualified;
11648 if (!UnqualifiedResult)
11649 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
11650 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
11651 }
11652 else
11653 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
11654 Unqualified);
11655 if (retType.isNull())
11656 return {};
11657
11658 if (Unqualified)
11659 retType = retType.getUnqualifiedType();
11660
11661 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
11662 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
11663 if (Unqualified) {
11664 LRetType = LRetType.getUnqualifiedType();
11665 RRetType = RRetType.getUnqualifiedType();
11666 }
11667
11668 if (getCanonicalType(retType) != LRetType)
11669 allLTypes = false;
11670 if (getCanonicalType(retType) != RRetType)
11671 allRTypes = false;
11672
11673 // FIXME: double check this
11674 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
11675 // rbase->getRegParmAttr() != 0 &&
11676 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
11677 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
11678 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
11679
11680 // Compatible functions must have compatible calling conventions
11681 if (lbaseInfo.getCC() != rbaseInfo.getCC())
11682 return {};
11683
11684 // Regparm is part of the calling convention.
11685 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
11686 return {};
11687 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
11688 return {};
11689
11690 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
11691 return {};
11692 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
11693 return {};
11694 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
11695 return {};
11696
11697 // When merging declarations, it's common for supplemental information like
11698 // attributes to only be present in one of the declarations, and we generally
11699 // want type merging to preserve the union of information. So a merged
11700 // function type should be noreturn if it was noreturn in *either* operand
11701 // type.
11702 //
11703 // But for the conditional operator, this is backwards. The result of the
11704 // operator could be either operand, and its type should conservatively
11705 // reflect that. So a function type in a composite type is noreturn only
11706 // if it's noreturn in *both* operand types.
11707 //
11708 // Arguably, noreturn is a kind of subtype, and the conditional operator
11709 // ought to produce the most specific common supertype of its operand types.
11710 // That would differ from this rule in contravariant positions. However,
11711 // neither C nor C++ generally uses this kind of subtype reasoning. Also,
11712 // as a practical matter, it would only affect C code that does abstraction of
11713 // higher-order functions (taking noreturn callbacks!), which is uncommon to
11714 // say the least. So we use the simpler rule.
11715 bool NoReturn = IsConditionalOperator
11716 ? lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn()
11717 : lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
11718 if (lbaseInfo.getNoReturn() != NoReturn)
11719 allLTypes = false;
11720 if (rbaseInfo.getNoReturn() != NoReturn)
11721 allRTypes = false;
11722
11723 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
11724
11725 std::optional<FunctionEffectSet> MergedFX;
11726
11727 if (lproto && rproto) { // two C99 style function prototypes
11728 assert((AllowCXX ||
11729 (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) &&
11730 "C++ shouldn't be here");
11731 // Compatible functions must have the same number of parameters
11732 if (lproto->getNumParams() != rproto->getNumParams())
11733 return {};
11734
11735 // Variadic and non-variadic functions aren't compatible
11736 if (lproto->isVariadic() != rproto->isVariadic())
11737 return {};
11738
11739 if (lproto->getMethodQuals() != rproto->getMethodQuals())
11740 return {};
11741
11742 // Function protos with different 'cfi_salt' values aren't compatible.
11743 if (lproto->getExtraAttributeInfo().CFISalt !=
11744 rproto->getExtraAttributeInfo().CFISalt)
11745 return {};
11746
11747 // Function effects are handled similarly to noreturn, see above.
11748 FunctionEffectsRef LHSFX = lproto->getFunctionEffects();
11749 FunctionEffectsRef RHSFX = rproto->getFunctionEffects();
11750 if (LHSFX != RHSFX) {
11751 if (IsConditionalOperator)
11752 MergedFX = FunctionEffectSet::getIntersection(LHSFX, RHSFX);
11753 else {
11755 MergedFX = FunctionEffectSet::getUnion(LHSFX, RHSFX, Errs);
11756 // Here we're discarding a possible error due to conflicts in the effect
11757 // sets. But we're not in a context where we can report it. The
11758 // operation does however guarantee maintenance of invariants.
11759 }
11760 if (*MergedFX != LHSFX)
11761 allLTypes = false;
11762 if (*MergedFX != RHSFX)
11763 allRTypes = false;
11764 }
11765
11767 bool canUseLeft, canUseRight;
11768 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
11769 newParamInfos))
11770 return {};
11771
11772 if (!canUseLeft)
11773 allLTypes = false;
11774 if (!canUseRight)
11775 allRTypes = false;
11776
11777 // Check parameter type compatibility
11779 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
11780 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
11781 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
11783 lParamType, rParamType, OfBlockPointer, Unqualified);
11784 if (paramType.isNull())
11785 return {};
11786
11787 if (Unqualified)
11788 paramType = paramType.getUnqualifiedType();
11789
11790 types.push_back(paramType);
11791 if (Unqualified) {
11792 lParamType = lParamType.getUnqualifiedType();
11793 rParamType = rParamType.getUnqualifiedType();
11794 }
11795
11796 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
11797 allLTypes = false;
11798 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
11799 allRTypes = false;
11800 }
11801
11802 if (allLTypes) return lhs;
11803 if (allRTypes) return rhs;
11804
11805 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
11806 EPI.ExtInfo = einfo;
11807 EPI.ExtParameterInfos =
11808 newParamInfos.empty() ? nullptr : newParamInfos.data();
11809 if (MergedFX)
11810 EPI.FunctionEffects = *MergedFX;
11811 return getFunctionType(retType, types, EPI);
11812 }
11813
11814 if (lproto) allRTypes = false;
11815 if (rproto) allLTypes = false;
11816
11817 const FunctionProtoType *proto = lproto ? lproto : rproto;
11818 if (proto) {
11819 assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here");
11820 if (proto->isVariadic())
11821 return {};
11822 // Check that the types are compatible with the types that
11823 // would result from default argument promotions (C99 6.7.5.3p15).
11824 // The only types actually affected are promotable integer
11825 // types and floats, which would be passed as a different
11826 // type depending on whether the prototype is visible.
11827 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
11828 QualType paramTy = proto->getParamType(i);
11829
11830 // Look at the converted type of enum types, since that is the type used
11831 // to pass enum values.
11832 if (const auto *ED = paramTy->getAsEnumDecl()) {
11833 paramTy = ED->getIntegerType();
11834 if (paramTy.isNull())
11835 return {};
11836 }
11837
11838 if (isPromotableIntegerType(paramTy) ||
11839 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
11840 return {};
11841 }
11842
11843 if (allLTypes) return lhs;
11844 if (allRTypes) return rhs;
11845
11847 EPI.ExtInfo = einfo;
11848 if (MergedFX)
11849 EPI.FunctionEffects = *MergedFX;
11850 return getFunctionType(retType, proto->getParamTypes(), EPI);
11851 }
11852
11853 if (allLTypes) return lhs;
11854 if (allRTypes) return rhs;
11855 return getFunctionNoProtoType(retType, einfo);
11856}
11857
11858/// Given that we have an enum type and a non-enum type, try to merge them.
11859static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
11860 QualType other, bool isBlockReturnType) {
11861 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
11862 // a signed integer type, or an unsigned integer type.
11863 // Compatibility is based on the underlying type, not the promotion
11864 // type.
11865 QualType underlyingType =
11866 ET->getDecl()->getDefinitionOrSelf()->getIntegerType();
11867 if (underlyingType.isNull())
11868 return {};
11869 if (Context.hasSameType(underlyingType, other))
11870 return other;
11871
11872 // In block return types, we're more permissive and accept any
11873 // integral type of the same size.
11874 if (isBlockReturnType && other->isIntegerType() &&
11875 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
11876 return other;
11877
11878 return {};
11879}
11880
11882 // C17 and earlier and C++ disallow two tag definitions within the same TU
11883 // from being compatible.
11884 if (LangOpts.CPlusPlus || !LangOpts.C23)
11885 return {};
11886
11887 // Nameless tags are comparable only within outer definitions. At the top
11888 // level they are not comparable.
11889 const TagDecl *LTagD = LHS->castAsTagDecl(), *RTagD = RHS->castAsTagDecl();
11890 if (!LTagD->getIdentifier() || !RTagD->getIdentifier())
11891 return {};
11892
11893 // C23, on the other hand, requires the members to be "the same enough", so
11894 // we use a structural equivalence check.
11897 getLangOpts(), *this, *this, NonEquivalentDecls,
11898 StructuralEquivalenceKind::Default, /*StrictTypeSpelling=*/false,
11899 /*Complain=*/false, /*ErrorOnTagTypeMismatch=*/true);
11900 return Ctx.IsEquivalent(LHS, RHS) ? LHS : QualType{};
11901}
11902
11904 QualType LHS, QualType RHS, bool OfBlockPointer, bool Unqualified,
11905 bool BlockReturnType, bool IsConditionalOperator) {
11906 const auto *LHSOBT = LHS->getAs<OverflowBehaviorType>();
11907 const auto *RHSOBT = RHS->getAs<OverflowBehaviorType>();
11908
11909 if (!LHSOBT && !RHSOBT)
11910 return std::nullopt;
11911
11912 if (LHSOBT) {
11913 if (RHSOBT) {
11914 if (LHSOBT->getBehaviorKind() != RHSOBT->getBehaviorKind())
11915 return QualType();
11916
11917 QualType MergedUnderlying = mergeTypes(
11918 LHSOBT->getUnderlyingType(), RHSOBT->getUnderlyingType(),
11919 OfBlockPointer, Unqualified, BlockReturnType, IsConditionalOperator);
11920
11921 if (MergedUnderlying.isNull())
11922 return QualType();
11923
11924 if (getCanonicalType(LHSOBT) == getCanonicalType(RHSOBT)) {
11925 if (LHSOBT->getUnderlyingType() == RHSOBT->getUnderlyingType())
11926 return getCommonSugaredType(LHS, RHS);
11928 LHSOBT->getBehaviorKind(),
11929 getCanonicalType(LHSOBT->getUnderlyingType()));
11930 }
11931
11932 // For different underlying types that successfully merge, wrap the
11933 // merged underlying type with the common overflow behavior
11934 return getOverflowBehaviorType(LHSOBT->getBehaviorKind(),
11935 MergedUnderlying);
11936 }
11937 return mergeTypes(LHSOBT->getUnderlyingType(), RHS, OfBlockPointer,
11938 Unqualified, BlockReturnType, IsConditionalOperator);
11939 }
11940
11941 return mergeTypes(LHS, RHSOBT->getUnderlyingType(), OfBlockPointer,
11942 Unqualified, BlockReturnType, IsConditionalOperator);
11943}
11944
11945QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
11946 bool Unqualified, bool BlockReturnType,
11947 bool IsConditionalOperator) {
11948 // For C++ we will not reach this code with reference types (see below),
11949 // for OpenMP variant call overloading we might.
11950 //
11951 // C++ [expr]: If an expression initially has the type "reference to T", the
11952 // type is adjusted to "T" prior to any further analysis, the expression
11953 // designates the object or function denoted by the reference, and the
11954 // expression is an lvalue unless the reference is an rvalue reference and
11955 // the expression is a function call (possibly inside parentheses).
11956 auto *LHSRefTy = LHS->getAs<ReferenceType>();
11957 auto *RHSRefTy = RHS->getAs<ReferenceType>();
11958 if (LangOpts.OpenMP && LHSRefTy && RHSRefTy &&
11959 LHS->getTypeClass() == RHS->getTypeClass())
11960 return mergeTypes(LHSRefTy->getPointeeType(), RHSRefTy->getPointeeType(),
11961 OfBlockPointer, Unqualified, BlockReturnType);
11962 if (LHSRefTy || RHSRefTy)
11963 return {};
11964
11965 if (std::optional<QualType> MergedOBT =
11966 tryMergeOverflowBehaviorTypes(LHS, RHS, OfBlockPointer, Unqualified,
11967 BlockReturnType, IsConditionalOperator))
11968 return *MergedOBT;
11969
11970 if (Unqualified) {
11971 LHS = LHS.getUnqualifiedType();
11972 RHS = RHS.getUnqualifiedType();
11973 }
11974
11975 QualType LHSCan = getCanonicalType(LHS),
11976 RHSCan = getCanonicalType(RHS);
11977
11978 // If two types are identical, they are compatible.
11979 if (LHSCan == RHSCan)
11980 return LHS;
11981
11982 // If the qualifiers are different, the types aren't compatible... mostly.
11983 Qualifiers LQuals = LHSCan.getLocalQualifiers();
11984 Qualifiers RQuals = RHSCan.getLocalQualifiers();
11985 if (LQuals != RQuals) {
11986 // If any of these qualifiers are different, we have a type
11987 // mismatch.
11988 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
11989 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
11990 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
11991 !LQuals.getPointerAuth().isEquivalent(RQuals.getPointerAuth()) ||
11992 LQuals.hasUnaligned() != RQuals.hasUnaligned())
11993 return {};
11994
11995 // Exactly one GC qualifier difference is allowed: __strong is
11996 // okay if the other type has no GC qualifier but is an Objective
11997 // C object pointer (i.e. implicitly strong by default). We fix
11998 // this by pretending that the unqualified type was actually
11999 // qualified __strong.
12000 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
12001 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
12002 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
12003
12004 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
12005 return {};
12006
12007 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
12009 }
12010 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
12012 }
12013 return {};
12014 }
12015
12016 // Okay, qualifiers are equal.
12017
12018 Type::TypeClass LHSClass = LHSCan->getTypeClass();
12019 Type::TypeClass RHSClass = RHSCan->getTypeClass();
12020
12021 // We want to consider the two function types to be the same for these
12022 // comparisons, just force one to the other.
12023 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
12024 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
12025
12026 // Same as above for arrays
12027 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
12028 LHSClass = Type::ConstantArray;
12029 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
12030 RHSClass = Type::ConstantArray;
12031
12032 // ObjCInterfaces are just specialized ObjCObjects.
12033 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
12034 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
12035
12036 // Canonicalize ExtVector -> Vector.
12037 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
12038 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
12039
12040 // If the canonical type classes don't match.
12041 if (LHSClass != RHSClass) {
12042 // Note that we only have special rules for turning block enum
12043 // returns into block int returns, not vice-versa.
12044 if (const auto *ETy = LHS->getAsCanonical<EnumType>()) {
12045 return mergeEnumWithInteger(*this, ETy, RHS, false);
12046 }
12047 if (const EnumType *ETy = RHS->getAsCanonical<EnumType>()) {
12048 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
12049 }
12050 // allow block pointer type to match an 'id' type.
12051 if (OfBlockPointer && !BlockReturnType) {
12052 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
12053 return LHS;
12054 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
12055 return RHS;
12056 }
12057 // Allow __auto_type to match anything; it merges to the type with more
12058 // information.
12059 if (const auto *AT = LHS->getAs<AutoType>()) {
12060 if (!AT->isDeduced() && AT->isGNUAutoType())
12061 return RHS;
12062 }
12063 if (const auto *AT = RHS->getAs<AutoType>()) {
12064 if (!AT->isDeduced() && AT->isGNUAutoType())
12065 return LHS;
12066 }
12067 return {};
12068 }
12069
12070 // The canonical type classes match.
12071 switch (LHSClass) {
12072#define TYPE(Class, Base)
12073#define ABSTRACT_TYPE(Class, Base)
12074#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
12075#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
12076#define DEPENDENT_TYPE(Class, Base) case Type::Class:
12077#include "clang/AST/TypeNodes.inc"
12078 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
12079
12080 case Type::Auto:
12081 case Type::DeducedTemplateSpecialization:
12082 case Type::LValueReference:
12083 case Type::RValueReference:
12084 case Type::MemberPointer:
12085 llvm_unreachable("C++ should never be in mergeTypes");
12086
12087 case Type::ObjCInterface:
12088 case Type::IncompleteArray:
12089 case Type::VariableArray:
12090 case Type::FunctionProto:
12091 case Type::ExtVector:
12092 case Type::OverflowBehavior:
12093 llvm_unreachable("Types are eliminated above");
12094
12095 case Type::Pointer:
12096 {
12097 // Merge two pointer types, while trying to preserve typedef info
12098 QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType();
12099 QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType();
12100 if (Unqualified) {
12101 LHSPointee = LHSPointee.getUnqualifiedType();
12102 RHSPointee = RHSPointee.getUnqualifiedType();
12103 }
12104 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
12105 Unqualified);
12106 if (ResultType.isNull())
12107 return {};
12108 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
12109 return LHS;
12110 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
12111 return RHS;
12112 return getPointerType(ResultType);
12113 }
12114 case Type::BlockPointer:
12115 {
12116 // Merge two block pointer types, while trying to preserve typedef info
12117 QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType();
12118 QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType();
12119 if (Unqualified) {
12120 LHSPointee = LHSPointee.getUnqualifiedType();
12121 RHSPointee = RHSPointee.getUnqualifiedType();
12122 }
12123 if (getLangOpts().OpenCL) {
12124 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
12125 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
12126 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
12127 // 6.12.5) thus the following check is asymmetric.
12128 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual, *this))
12129 return {};
12130 LHSPteeQual.removeAddressSpace();
12131 RHSPteeQual.removeAddressSpace();
12132 LHSPointee =
12133 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
12134 RHSPointee =
12135 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
12136 }
12137 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
12138 Unqualified);
12139 if (ResultType.isNull())
12140 return {};
12141 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
12142 return LHS;
12143 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
12144 return RHS;
12145 return getBlockPointerType(ResultType);
12146 }
12147 case Type::Atomic:
12148 {
12149 // Merge two pointer types, while trying to preserve typedef info
12150 QualType LHSValue = LHS->castAs<AtomicType>()->getValueType();
12151 QualType RHSValue = RHS->castAs<AtomicType>()->getValueType();
12152 if (Unqualified) {
12153 LHSValue = LHSValue.getUnqualifiedType();
12154 RHSValue = RHSValue.getUnqualifiedType();
12155 }
12156 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
12157 Unqualified);
12158 if (ResultType.isNull())
12159 return {};
12160 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
12161 return LHS;
12162 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
12163 return RHS;
12164 return getAtomicType(ResultType);
12165 }
12166 case Type::ConstantArray:
12167 {
12168 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
12169 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
12170 if (LCAT && RCAT && RCAT->getZExtSize() != LCAT->getZExtSize())
12171 return {};
12172
12173 QualType LHSElem = getAsArrayType(LHS)->getElementType();
12174 QualType RHSElem = getAsArrayType(RHS)->getElementType();
12175 if (Unqualified) {
12176 LHSElem = LHSElem.getUnqualifiedType();
12177 RHSElem = RHSElem.getUnqualifiedType();
12178 }
12179
12180 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
12181 if (ResultType.isNull())
12182 return {};
12183
12184 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
12185 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
12186
12187 // If either side is a variable array, and both are complete, check whether
12188 // the current dimension is definite.
12189 if (LVAT || RVAT) {
12190 auto SizeFetch = [this](const VariableArrayType* VAT,
12191 const ConstantArrayType* CAT)
12192 -> std::pair<bool,llvm::APInt> {
12193 if (VAT) {
12194 std::optional<llvm::APSInt> TheInt;
12195 Expr *E = VAT->getSizeExpr();
12196 if (E && (TheInt = E->getIntegerConstantExpr(*this)))
12197 return std::make_pair(true, *TheInt);
12198 return std::make_pair(false, llvm::APSInt());
12199 }
12200 if (CAT)
12201 return std::make_pair(true, CAT->getSize());
12202 return std::make_pair(false, llvm::APInt());
12203 };
12204
12205 bool HaveLSize, HaveRSize;
12206 llvm::APInt LSize, RSize;
12207 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
12208 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
12209 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
12210 return {}; // Definite, but unequal, array dimension
12211 }
12212
12213 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
12214 return LHS;
12215 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
12216 return RHS;
12217 if (LCAT)
12218 return getConstantArrayType(ResultType, LCAT->getSize(),
12219 LCAT->getSizeExpr(), ArraySizeModifier(), 0);
12220 if (RCAT)
12221 return getConstantArrayType(ResultType, RCAT->getSize(),
12222 RCAT->getSizeExpr(), ArraySizeModifier(), 0);
12223 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
12224 return LHS;
12225 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
12226 return RHS;
12227 if (LVAT) {
12228 // FIXME: This isn't correct! But tricky to implement because
12229 // the array's size has to be the size of LHS, but the type
12230 // has to be different.
12231 return LHS;
12232 }
12233 if (RVAT) {
12234 // FIXME: This isn't correct! But tricky to implement because
12235 // the array's size has to be the size of RHS, but the type
12236 // has to be different.
12237 return RHS;
12238 }
12239 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
12240 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
12241 return getIncompleteArrayType(ResultType, ArraySizeModifier(), 0);
12242 }
12243 case Type::FunctionNoProto:
12244 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified,
12245 /*AllowCXX=*/false, IsConditionalOperator);
12246 case Type::Record:
12247 case Type::Enum:
12248 return mergeTagDefinitions(LHS, RHS);
12249 case Type::Builtin:
12250 // Only exactly equal builtin types are compatible, which is tested above.
12251 return {};
12252 case Type::Complex:
12253 // Distinct complex types are incompatible.
12254 return {};
12255 case Type::Vector:
12256 // FIXME: The merged type should be an ExtVector!
12257 if (areCompatVectorTypes(LHSCan->castAs<VectorType>(),
12258 RHSCan->castAs<VectorType>()))
12259 return LHS;
12260 return {};
12261 case Type::ConstantMatrix:
12263 RHSCan->castAs<ConstantMatrixType>()))
12264 return LHS;
12265 return {};
12266 case Type::ObjCObject: {
12267 // Check if the types are assignment compatible.
12268 // FIXME: This should be type compatibility, e.g. whether
12269 // "LHS x; RHS x;" at global scope is legal.
12271 RHS->castAs<ObjCObjectType>()))
12272 return LHS;
12273 return {};
12274 }
12275 case Type::ObjCObjectPointer:
12276 if (OfBlockPointer) {
12279 RHS->castAs<ObjCObjectPointerType>(), BlockReturnType))
12280 return LHS;
12281 return {};
12282 }
12285 return LHS;
12286 return {};
12287 case Type::Pipe:
12288 assert(LHS != RHS &&
12289 "Equivalent pipe types should have already been handled!");
12290 return {};
12291 case Type::ArrayParameter:
12292 assert(LHS != RHS &&
12293 "Equivalent ArrayParameter types should have already been handled!");
12294 return {};
12295 case Type::BitInt: {
12296 // Merge two bit-precise int types, while trying to preserve typedef info.
12297 bool LHSUnsigned = LHS->castAs<BitIntType>()->isUnsigned();
12298 bool RHSUnsigned = RHS->castAs<BitIntType>()->isUnsigned();
12299 unsigned LHSBits = LHS->castAs<BitIntType>()->getNumBits();
12300 unsigned RHSBits = RHS->castAs<BitIntType>()->getNumBits();
12301
12302 // Like unsigned/int, shouldn't have a type if they don't match.
12303 if (LHSUnsigned != RHSUnsigned)
12304 return {};
12305
12306 if (LHSBits != RHSBits)
12307 return {};
12308 return LHS;
12309 }
12310 case Type::HLSLAttributedResource: {
12311 const HLSLAttributedResourceType *LHSTy =
12312 LHS->castAs<HLSLAttributedResourceType>();
12313 const HLSLAttributedResourceType *RHSTy =
12314 RHS->castAs<HLSLAttributedResourceType>();
12315 assert(LHSTy->getWrappedType() == RHSTy->getWrappedType() &&
12316 LHSTy->getWrappedType()->isHLSLResourceType() &&
12317 "HLSLAttributedResourceType should always wrap __hlsl_resource_t");
12318
12319 if (LHSTy->getAttrs() == RHSTy->getAttrs() &&
12320 LHSTy->getContainedType() == RHSTy->getContainedType())
12321 return LHS;
12322 return {};
12323 }
12324 case Type::HLSLInlineSpirv:
12325 const HLSLInlineSpirvType *LHSTy = LHS->castAs<HLSLInlineSpirvType>();
12326 const HLSLInlineSpirvType *RHSTy = RHS->castAs<HLSLInlineSpirvType>();
12327
12328 if (LHSTy->getOpcode() == RHSTy->getOpcode() &&
12329 LHSTy->getSize() == RHSTy->getSize() &&
12330 LHSTy->getAlignment() == RHSTy->getAlignment()) {
12331 for (size_t I = 0; I < LHSTy->getOperands().size(); I++)
12332 if (LHSTy->getOperands()[I] != RHSTy->getOperands()[I])
12333 return {};
12334
12335 return LHS;
12336 }
12337 return {};
12338 }
12339
12340 llvm_unreachable("Invalid Type::Class!");
12341}
12342
12344 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
12345 bool &CanUseFirst, bool &CanUseSecond,
12347 assert(NewParamInfos.empty() && "param info list not empty");
12348 CanUseFirst = CanUseSecond = true;
12349 bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
12350 bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
12351
12352 // Fast path: if the first type doesn't have ext parameter infos,
12353 // we match if and only if the second type also doesn't have them.
12354 if (!FirstHasInfo && !SecondHasInfo)
12355 return true;
12356
12357 bool NeedParamInfo = false;
12358 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
12359 : SecondFnType->getExtParameterInfos().size();
12360
12361 for (size_t I = 0; I < E; ++I) {
12362 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
12363 if (FirstHasInfo)
12364 FirstParam = FirstFnType->getExtParameterInfo(I);
12365 if (SecondHasInfo)
12366 SecondParam = SecondFnType->getExtParameterInfo(I);
12367
12368 // Cannot merge unless everything except the noescape flag matches.
12369 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
12370 return false;
12371
12372 bool FirstNoEscape = FirstParam.isNoEscape();
12373 bool SecondNoEscape = SecondParam.isNoEscape();
12374 bool IsNoEscape = FirstNoEscape && SecondNoEscape;
12375 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
12376 if (NewParamInfos.back().getOpaqueValue())
12377 NeedParamInfo = true;
12378 if (FirstNoEscape != IsNoEscape)
12379 CanUseFirst = false;
12380 if (SecondNoEscape != IsNoEscape)
12381 CanUseSecond = false;
12382 }
12383
12384 if (!NeedParamInfo)
12385 NewParamInfos.clear();
12386
12387 return true;
12388}
12389
12391 if (auto It = ObjCLayouts.find(D); It != ObjCLayouts.end()) {
12392 It->second = nullptr;
12393 for (auto *SubClass : ObjCSubClasses.lookup(D))
12394 ResetObjCLayout(SubClass);
12395 }
12396}
12397
12398/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
12399/// 'RHS' attributes and returns the merged version; including for function
12400/// return types.
12402 QualType LHSCan = getCanonicalType(LHS),
12403 RHSCan = getCanonicalType(RHS);
12404 // If two types are identical, they are compatible.
12405 if (LHSCan == RHSCan)
12406 return LHS;
12407 if (RHSCan->isFunctionType()) {
12408 if (!LHSCan->isFunctionType())
12409 return {};
12410 QualType OldReturnType =
12411 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
12412 QualType NewReturnType =
12413 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
12414 QualType ResReturnType =
12415 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
12416 if (ResReturnType.isNull())
12417 return {};
12418 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
12419 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
12420 // In either case, use OldReturnType to build the new function type.
12421 const auto *F = LHS->castAs<FunctionType>();
12422 if (const auto *FPT = cast<FunctionProtoType>(F)) {
12423 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12424 EPI.ExtInfo = getFunctionExtInfo(LHS);
12425 QualType ResultType =
12426 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
12427 return ResultType;
12428 }
12429 }
12430 return {};
12431 }
12432
12433 // If the qualifiers are different, the types can still be merged.
12434 Qualifiers LQuals = LHSCan.getLocalQualifiers();
12435 Qualifiers RQuals = RHSCan.getLocalQualifiers();
12436
12437 if (LQuals.withoutObjCGCAttr() != RQuals.withoutObjCGCAttr()) {
12438 // Reject immediately, if anything but the GC qualifiers is different.
12439 return {};
12440 }
12441
12442 if (LQuals != RQuals) {
12443 // Exactly one GC qualifier difference is allowed: __strong is
12444 // okay if the other type has no GC qualifier but is an Objective
12445 // C object pointer (i.e. implicitly strong by default). We fix
12446 // this by pretending that the unqualified type was actually
12447 // qualified __strong.
12448 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
12449 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
12450 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
12451
12452 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
12453 return {};
12454
12455 if (GC_L == Qualifiers::Strong)
12456 return LHS;
12457 if (GC_R == Qualifiers::Strong)
12458 return RHS;
12459 return {};
12460 }
12461
12462 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
12463 QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType();
12464 QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType();
12465 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
12466 if (ResQT == LHSBaseQT)
12467 return LHS;
12468 if (ResQT == RHSBaseQT)
12469 return RHS;
12470 }
12471 return {};
12472}
12473
12474//===----------------------------------------------------------------------===//
12475// Integer Predicates
12476//===----------------------------------------------------------------------===//
12477
12479 if (const auto *ED = T->getAsEnumDecl())
12480 T = ED->getIntegerType();
12481 if (T->isBooleanType())
12482 return 1;
12483 if (const auto *EIT = T->getAs<BitIntType>())
12484 return EIT->getNumBits();
12485 // For builtin types, just use the standard type sizing method
12486 return (unsigned)getTypeSize(T);
12487}
12488
12490 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
12491 T->isFixedPointType()) &&
12492 "Unexpected type");
12493
12494 // Turn <4 x signed int> -> <4 x unsigned int>
12495 if (const auto *VTy = T->getAs<VectorType>())
12496 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
12497 VTy->getNumElements(), VTy->getVectorKind());
12498
12499 // For _BitInt, return an unsigned _BitInt with same width.
12500 if (const auto *EITy = T->getAs<BitIntType>())
12501 return getBitIntType(/*Unsigned=*/true, EITy->getNumBits());
12502
12503 // For the overflow behavior types, construct a new unsigned variant
12504 if (const auto *OBT = T->getAs<OverflowBehaviorType>())
12506 OBT->getBehaviorKind(),
12507 getCorrespondingUnsignedType(OBT->getUnderlyingType()));
12508
12509 // For enums, get the underlying integer type of the enum, and let the general
12510 // integer type signchanging code handle it.
12511 if (const auto *ED = T->getAsEnumDecl())
12512 T = ED->getIntegerType();
12513
12514 switch (T->castAs<BuiltinType>()->getKind()) {
12515 case BuiltinType::Char_U:
12516 // Plain `char` is mapped to `unsigned char` even if it's already unsigned
12517 case BuiltinType::Char_S:
12518 case BuiltinType::SChar:
12519 case BuiltinType::Char8:
12520 return UnsignedCharTy;
12521 case BuiltinType::Short:
12522 return UnsignedShortTy;
12523 case BuiltinType::Int:
12524 return UnsignedIntTy;
12525 case BuiltinType::Long:
12526 return UnsignedLongTy;
12527 case BuiltinType::LongLong:
12528 return UnsignedLongLongTy;
12529 case BuiltinType::Int128:
12530 return UnsignedInt128Ty;
12531 // wchar_t is special. It is either signed or not, but when it's signed,
12532 // there's no matching "unsigned wchar_t". Therefore we return the unsigned
12533 // version of its underlying type instead.
12534 case BuiltinType::WChar_S:
12535 return getUnsignedWCharType();
12536
12537 case BuiltinType::ShortAccum:
12538 return UnsignedShortAccumTy;
12539 case BuiltinType::Accum:
12540 return UnsignedAccumTy;
12541 case BuiltinType::LongAccum:
12542 return UnsignedLongAccumTy;
12543 case BuiltinType::SatShortAccum:
12545 case BuiltinType::SatAccum:
12546 return SatUnsignedAccumTy;
12547 case BuiltinType::SatLongAccum:
12549 case BuiltinType::ShortFract:
12550 return UnsignedShortFractTy;
12551 case BuiltinType::Fract:
12552 return UnsignedFractTy;
12553 case BuiltinType::LongFract:
12554 return UnsignedLongFractTy;
12555 case BuiltinType::SatShortFract:
12557 case BuiltinType::SatFract:
12558 return SatUnsignedFractTy;
12559 case BuiltinType::SatLongFract:
12561 default:
12562 assert((T->hasUnsignedIntegerRepresentation() ||
12563 T->isUnsignedFixedPointType()) &&
12564 "Unexpected signed integer or fixed point type");
12565 return T;
12566 }
12567}
12568
12570 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
12571 T->isFixedPointType()) &&
12572 "Unexpected type");
12573
12574 // Turn <4 x unsigned int> -> <4 x signed int>
12575 if (const auto *VTy = T->getAs<VectorType>())
12576 return getVectorType(getCorrespondingSignedType(VTy->getElementType()),
12577 VTy->getNumElements(), VTy->getVectorKind());
12578
12579 // For _BitInt, return a signed _BitInt with same width.
12580 if (const auto *EITy = T->getAs<BitIntType>())
12581 return getBitIntType(/*Unsigned=*/false, EITy->getNumBits());
12582
12583 // For enums, get the underlying integer type of the enum, and let the general
12584 // integer type signchanging code handle it.
12585 if (const auto *ED = T->getAsEnumDecl())
12586 T = ED->getIntegerType();
12587
12588 switch (T->castAs<BuiltinType>()->getKind()) {
12589 case BuiltinType::Char_S:
12590 // Plain `char` is mapped to `signed char` even if it's already signed
12591 case BuiltinType::Char_U:
12592 case BuiltinType::UChar:
12593 case BuiltinType::Char8:
12594 return SignedCharTy;
12595 case BuiltinType::UShort:
12596 return ShortTy;
12597 case BuiltinType::UInt:
12598 return IntTy;
12599 case BuiltinType::ULong:
12600 return LongTy;
12601 case BuiltinType::ULongLong:
12602 return LongLongTy;
12603 case BuiltinType::UInt128:
12604 return Int128Ty;
12605 // wchar_t is special. It is either unsigned or not, but when it's unsigned,
12606 // there's no matching "signed wchar_t". Therefore we return the signed
12607 // version of its underlying type instead.
12608 case BuiltinType::WChar_U:
12609 return getSignedWCharType();
12610
12611 case BuiltinType::UShortAccum:
12612 return ShortAccumTy;
12613 case BuiltinType::UAccum:
12614 return AccumTy;
12615 case BuiltinType::ULongAccum:
12616 return LongAccumTy;
12617 case BuiltinType::SatUShortAccum:
12618 return SatShortAccumTy;
12619 case BuiltinType::SatUAccum:
12620 return SatAccumTy;
12621 case BuiltinType::SatULongAccum:
12622 return SatLongAccumTy;
12623 case BuiltinType::UShortFract:
12624 return ShortFractTy;
12625 case BuiltinType::UFract:
12626 return FractTy;
12627 case BuiltinType::ULongFract:
12628 return LongFractTy;
12629 case BuiltinType::SatUShortFract:
12630 return SatShortFractTy;
12631 case BuiltinType::SatUFract:
12632 return SatFractTy;
12633 case BuiltinType::SatULongFract:
12634 return SatLongFractTy;
12635 default:
12636 assert(
12637 (T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) &&
12638 "Unexpected signed integer or fixed point type");
12639 return T;
12640 }
12641}
12642
12644
12647
12648//===----------------------------------------------------------------------===//
12649// Builtin Type Computation
12650//===----------------------------------------------------------------------===//
12651
12652/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
12653/// pointer over the consumed characters. This returns the resultant type. If
12654/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
12655/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
12656/// a vector of "i*".
12657///
12658/// RequiresICE is filled in on return to indicate whether the value is required
12659/// to be an Integer Constant Expression.
12660static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
12662 bool &RequiresICE,
12663 bool AllowTypeModifiers) {
12664 // Modifiers.
12665 int HowLong = 0;
12666 bool Signed = false, Unsigned = false;
12667 bool IsChar = false, IsShort = false;
12668 bool IsLeast = false;
12669 RequiresICE = false;
12670
12671 // Read the prefixed modifiers first.
12672 bool Done = false;
12673 #ifndef NDEBUG
12674 bool IsSpecial = false;
12675 #endif
12676 while (!Done) {
12677 switch (*Str++) {
12678 default: Done = true; --Str; break;
12679 case 'I':
12680 RequiresICE = true;
12681 break;
12682 case 'S':
12683 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
12684 assert(!Signed && "Can't use 'S' modifier multiple times!");
12685 Signed = true;
12686 break;
12687 case 'U':
12688 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
12689 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
12690 Unsigned = true;
12691 break;
12692 case 'l':
12693 // This modifier represents the least-width type (e.g. uint_least8_t).
12694 assert(!IsLeast && "Can't use 'l' modifier multiple times!");
12695 IsLeast = true;
12696 break;
12697 case 'B':
12698 // This modifier represents int8 type (byte-width).
12699 assert(!IsSpecial &&
12700 "Can't use two 'N', 'W', 'Z', 'O', 'B', or 'T' modifiers!");
12701 assert(HowLong == 0 && "Can't use both 'L' and 'B' modifiers!");
12702#ifndef NDEBUG
12703 IsSpecial = true;
12704#endif
12705 IsChar = true;
12706 break;
12707 case 'T':
12708 // This modifier represents int16 type (short-width).
12709 assert(!IsSpecial &&
12710 "Can't use two 'N', 'W', 'Z', 'O', 'B', or 'T' modifiers!");
12711 assert(HowLong == 0 && "Can't use both 'L' and 'T' modifiers!");
12712#ifndef NDEBUG
12713 IsSpecial = true;
12714#endif
12715 IsShort = true;
12716 break;
12717 case 'L':
12718 assert(!IsSpecial &&
12719 "Can't use 'L' with 'W', 'N', 'Z', 'O', 'B', or 'T' modifiers");
12720 assert(HowLong <= 2 && "Can't have LLLL modifier");
12721 ++HowLong;
12722 break;
12723 case 'N':
12724 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
12725 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12726 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
12727 #ifndef NDEBUG
12728 IsSpecial = true;
12729 #endif
12730 if (Context.getTargetInfo().getLongWidth() == 32)
12731 ++HowLong;
12732 break;
12733 case 'W':
12734 // This modifier represents int64 type.
12735 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12736 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
12737 #ifndef NDEBUG
12738 IsSpecial = true;
12739 #endif
12740 switch (Context.getTargetInfo().getInt64Type()) {
12741 default:
12742 llvm_unreachable("Unexpected integer type");
12744 HowLong = 1;
12745 break;
12747 HowLong = 2;
12748 break;
12749 }
12750 break;
12751 case 'Z':
12752 // This modifier represents int32 type.
12753 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12754 assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
12755 #ifndef NDEBUG
12756 IsSpecial = true;
12757 #endif
12758 switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) {
12759 default:
12760 llvm_unreachable("Unexpected integer type");
12762 HowLong = 0;
12763 break;
12765 HowLong = 1;
12766 break;
12768 HowLong = 2;
12769 break;
12770 }
12771 break;
12772 case 'O':
12773 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12774 assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
12775 #ifndef NDEBUG
12776 IsSpecial = true;
12777 #endif
12778 if (Context.getLangOpts().OpenCL)
12779 HowLong = 1;
12780 else
12781 HowLong = 2;
12782 break;
12783 }
12784 }
12785
12786 QualType Type;
12787
12788 // Read the base type.
12789 switch (*Str++) {
12790 default:
12791 llvm_unreachable("Unknown builtin type letter!");
12792 case 'x':
12793 assert(HowLong == 0 && !Signed && !Unsigned &&
12794 "Bad modifiers used with 'x'!");
12795 Type = Context.Float16Ty;
12796 break;
12797 case 'y':
12798 assert(HowLong == 0 && !Signed && !Unsigned &&
12799 "Bad modifiers used with 'y'!");
12800 Type = Context.BFloat16Ty;
12801 break;
12802 case 'v':
12803 assert(HowLong == 0 && !Signed && !Unsigned &&
12804 "Bad modifiers used with 'v'!");
12805 Type = Context.VoidTy;
12806 break;
12807 case 'h':
12808 assert(HowLong == 0 && !Signed && !Unsigned &&
12809 "Bad modifiers used with 'h'!");
12810 Type = Context.HalfTy;
12811 break;
12812 case 'f':
12813 assert(HowLong == 0 && !Signed && !Unsigned &&
12814 "Bad modifiers used with 'f'!");
12815 Type = Context.FloatTy;
12816 break;
12817 case 'd':
12818 assert(HowLong < 3 && !Signed && !Unsigned &&
12819 "Bad modifiers used with 'd'!");
12820 if (HowLong == 1)
12821 Type = Context.LongDoubleTy;
12822 else if (HowLong == 2)
12823 Type = Context.Float128Ty;
12824 else
12825 Type = Context.DoubleTy;
12826 break;
12827 case 's':
12828 assert(HowLong == 0 && "Bad modifiers used with 's'!");
12829 if (Unsigned)
12830 Type = Context.UnsignedShortTy;
12831 else
12832 Type = Context.ShortTy;
12833 break;
12834 case 'i':
12835 if (IsChar)
12836 Type = Unsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
12837 else if (IsShort)
12838 Type = Unsigned ? Context.UnsignedShortTy : Context.ShortTy;
12839 else if (HowLong == 3)
12840 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
12841 else if (HowLong == 2)
12842 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
12843 else if (HowLong == 1)
12844 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
12845 else
12846 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
12847 if (IsLeast)
12848 Type = Context.getLeastIntTypeForBitwidth(Context.getIntWidth(Type),
12849 /*Signed=*/!Unsigned);
12850 break;
12851 case 'c':
12852 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
12853 if (Signed)
12854 Type = Context.SignedCharTy;
12855 else if (Unsigned)
12856 Type = Context.UnsignedCharTy;
12857 else
12858 Type = Context.CharTy;
12859 break;
12860 case 'b': // boolean
12861 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
12862 Type = Context.BoolTy;
12863 break;
12864 case 'z': // size_t.
12865 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
12866 Type = Context.getSizeType();
12867 break;
12868 case 'w': // wchar_t.
12869 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
12870 Type = Context.getWideCharType();
12871 break;
12872 case 'F':
12873 Type = Context.getCFConstantStringType();
12874 break;
12875 case 'G':
12876 Type = Context.getObjCIdType();
12877 break;
12878 case 'H':
12879 Type = Context.getObjCSelType();
12880 break;
12881 case 'M':
12882 Type = Context.getObjCSuperType();
12883 break;
12884 case 'r':
12885 Type = Context.MetaInfoTy;
12886 break;
12887 case 'a':
12888 Type = Context.getBuiltinVaListType();
12889 assert(!Type.isNull() && "builtin va list type not initialized!");
12890 break;
12891 case 'A':
12892 // This is a "reference" to a va_list; however, what exactly
12893 // this means depends on how va_list is defined. There are two
12894 // different kinds of va_list: ones passed by value, and ones
12895 // passed by reference. An example of a by-value va_list is
12896 // x86, where va_list is a char*. An example of by-ref va_list
12897 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
12898 // we want this argument to be a char*&; for x86-64, we want
12899 // it to be a __va_list_tag*.
12900 Type = Context.getBuiltinVaListType();
12901 assert(!Type.isNull() && "builtin va list type not initialized!");
12902 if (Type->isArrayType())
12903 Type = Context.getArrayDecayedType(Type);
12904 else
12905 Type = Context.getLValueReferenceType(Type);
12906 break;
12907 case 'q': {
12908 char *End;
12909 unsigned NumElements = strtoul(Str, &End, 10);
12910 assert(End != Str && "Missing vector size");
12911 Str = End;
12912
12913 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12914 RequiresICE, false);
12915 assert(!RequiresICE && "Can't require vector ICE");
12916
12917 Type = Context.getScalableVectorType(ElementType, NumElements);
12918 break;
12919 }
12920 case 'Q': {
12921 switch (*Str++) {
12922 case 'a': {
12923 Type = Context.SveCountTy;
12924 break;
12925 }
12926 case 'b': {
12927 Type = Context.AMDGPUBufferRsrcTy;
12928 break;
12929 }
12930 case 'c': {
12931 Type = Context.AMDGPUFeaturePredicateTy;
12932 break;
12933 }
12934 case 't': {
12935 Type = Context.AMDGPUTextureTy;
12936 break;
12937 }
12938 case 'r': {
12939 Type = Context.HLSLResourceTy;
12940 break;
12941 }
12942 default:
12943 llvm_unreachable("Unexpected target builtin type");
12944 }
12945 break;
12946 }
12947 case 'V': {
12948 char *End;
12949 unsigned NumElements = strtoul(Str, &End, 10);
12950 assert(End != Str && "Missing vector size");
12951 Str = End;
12952
12953 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12954 RequiresICE, false);
12955 assert(!RequiresICE && "Can't require vector ICE");
12956
12957 // TODO: No way to make AltiVec vectors in builtins yet.
12958 Type = Context.getVectorType(ElementType, NumElements, VectorKind::Generic);
12959 break;
12960 }
12961 case 'E': {
12962 char *End;
12963
12964 unsigned NumElements = strtoul(Str, &End, 10);
12965 assert(End != Str && "Missing vector size");
12966
12967 Str = End;
12968
12969 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12970 false);
12971 Type = Context.getExtVectorType(ElementType, NumElements);
12972 break;
12973 }
12974 case 'X': {
12975 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12976 false);
12977 assert(!RequiresICE && "Can't require complex ICE");
12978 Type = Context.getComplexType(ElementType);
12979 break;
12980 }
12981 case 'Y':
12982 Type = Context.getPointerDiffType();
12983 break;
12984 case 'P':
12985 Type = Context.getFILEType();
12986 if (Type.isNull()) {
12988 return {};
12989 }
12990 break;
12991 case 'J':
12992 if (Signed)
12993 Type = Context.getsigjmp_bufType();
12994 else
12995 Type = Context.getjmp_bufType();
12996
12997 if (Type.isNull()) {
12999 return {};
13000 }
13001 break;
13002 case 'K':
13003 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
13004 Type = Context.getucontext_tType();
13005
13006 if (Type.isNull()) {
13008 return {};
13009 }
13010 break;
13011 case 'p':
13012 Type = Context.getProcessIDType();
13013 break;
13014 case 'm':
13015 Type = Context.MFloat8Ty;
13016 break;
13017 }
13018
13019 // If there are modifiers and if we're allowed to parse them, go for it.
13020 Done = !AllowTypeModifiers;
13021 while (!Done) {
13022 switch (char c = *Str++) {
13023 default: Done = true; --Str; break;
13024 case '*':
13025 case '&': {
13026 // Both pointers and references can have their pointee types
13027 // qualified with an address space.
13028 char *End;
13029 unsigned AddrSpace = strtoul(Str, &End, 10);
13030 if (End != Str) {
13031 // Note AddrSpace == 0 is not the same as an unspecified address space.
13032 Type = Context.getAddrSpaceQualType(
13033 Type,
13034 Context.getLangASForBuiltinAddressSpace(AddrSpace));
13035 Str = End;
13036 }
13037 if (c == '*')
13038 Type = Context.getPointerType(Type);
13039 else
13040 Type = Context.getLValueReferenceType(Type);
13041 break;
13042 }
13043 // FIXME: There's no way to have a built-in with an rvalue ref arg.
13044 case 'C':
13045 Type = Type.withConst();
13046 break;
13047 case 'D':
13048 Type = Context.getVolatileType(Type);
13049 break;
13050 case 'R':
13051 Type = Type.withRestrict();
13052 break;
13053 }
13054 }
13055
13056 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
13057 "Integer constant 'I' type must be an integer");
13058
13059 return Type;
13060}
13061
13062// On some targets such as PowerPC, some of the builtins are defined with custom
13063// type descriptors for target-dependent types. These descriptors are decoded in
13064// other functions, but it may be useful to be able to fall back to default
13065// descriptor decoding to define builtins mixing target-dependent and target-
13066// independent types. This function allows decoding one type descriptor with
13067// default decoding.
13068QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context,
13069 GetBuiltinTypeError &Error, bool &RequireICE,
13070 bool AllowTypeModifiers) const {
13071 return DecodeTypeFromStr(Str, Context, Error, RequireICE, AllowTypeModifiers);
13072}
13073
13074/// GetBuiltinType - Return the type for the specified builtin.
13077 unsigned *IntegerConstantArgs) const {
13078 const char *TypeStr = BuiltinInfo.getTypeString(Id);
13079 if (TypeStr[0] == '\0') {
13081 return {};
13082 }
13083
13084 SmallVector<QualType, 8> ArgTypes;
13085
13086 bool RequiresICE = false;
13087 Error = GE_None;
13088 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
13089 RequiresICE, true);
13090 if (Error != GE_None)
13091 return {};
13092
13093 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
13094
13095 while (TypeStr[0] && TypeStr[0] != '.') {
13096 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
13097 if (Error != GE_None)
13098 return {};
13099
13100 // If this argument is required to be an IntegerConstantExpression and the
13101 // caller cares, fill in the bitmask we return.
13102 if (RequiresICE && IntegerConstantArgs)
13103 *IntegerConstantArgs |= 1 << ArgTypes.size();
13104
13105 // Do array -> pointer decay. The builtin should use the decayed type.
13106 if (Ty->isArrayType())
13107 Ty = getArrayDecayedType(Ty);
13108
13109 ArgTypes.push_back(Ty);
13110 }
13111
13112 if (Id == Builtin::BI__GetExceptionInfo)
13113 return {};
13114
13115 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
13116 "'.' should only occur at end of builtin type list!");
13117
13118 bool Variadic = (TypeStr[0] == '.');
13119
13120 FunctionType::ExtInfo EI(Target->getDefaultCallingConv());
13121 if (BuiltinInfo.isNoReturn(Id))
13122 EI = EI.withNoReturn(true);
13123
13124 // We really shouldn't be making a no-proto type here.
13125 if (ArgTypes.empty() && Variadic && !getLangOpts().requiresStrictPrototypes())
13126 return getFunctionNoProtoType(ResType, EI);
13127
13129 EPI.ExtInfo = EI;
13130 EPI.Variadic = Variadic;
13131 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
13132 EPI.ExceptionSpec.Type =
13134
13135 return getFunctionType(ResType, ArgTypes, EPI);
13136}
13137
13139 const FunctionDecl *FD) {
13140 if (!FD->isExternallyVisible())
13141 return GVA_Internal;
13142
13143 // Non-user-provided functions get emitted as weak definitions with every
13144 // use, no matter whether they've been explicitly instantiated etc.
13145 if (!FD->isUserProvided())
13146 return GVA_DiscardableODR;
13147
13149 switch (FD->getTemplateSpecializationKind()) {
13150 case TSK_Undeclared:
13153 break;
13154
13156 return GVA_StrongODR;
13157
13158 // C++11 [temp.explicit]p10:
13159 // [ Note: The intent is that an inline function that is the subject of
13160 // an explicit instantiation declaration will still be implicitly
13161 // instantiated when used so that the body can be considered for
13162 // inlining, but that no out-of-line copy of the inline function would be
13163 // generated in the translation unit. -- end note ]
13166
13169 break;
13170 }
13171
13172 if (!FD->isInlined())
13173 return External;
13174
13175 if ((!Context.getLangOpts().CPlusPlus &&
13176 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13177 !FD->hasAttr<DLLExportAttr>()) ||
13178 FD->hasAttr<GNUInlineAttr>()) {
13179 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
13180
13181 // GNU or C99 inline semantics. Determine whether this symbol should be
13182 // externally visible.
13183 if (auto *Def = FD->getDefinition();
13185 return External;
13186
13187 // C99 inline semantics, where the symbol is not externally visible.
13189 }
13190
13191 // Functions specified with extern and inline in -fms-compatibility mode
13192 // forcibly get emitted. While the body of the function cannot be later
13193 // replaced, the function definition cannot be discarded.
13194 if (FD->isMSExternInline())
13195 return GVA_StrongODR;
13196
13197 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13199 cast<CXXConstructorDecl>(FD)->isInheritingConstructor() &&
13200 !FD->hasAttr<DLLExportAttr>()) {
13201 // Both Clang and MSVC implement inherited constructors as forwarding
13202 // thunks that delegate to the base constructor. Keep non-dllexport
13203 // inheriting constructor thunks internal since they are not needed
13204 // outside the translation unit.
13205 //
13206 // dllexport inherited constructors are exempted so they are externally
13207 // visible, matching MSVC's export behavior. Inherited constructors
13208 // whose parameters prevent ABI-compatible forwarding (e.g. callee-
13209 // cleanup types) are excluded from export in Sema to avoid silent
13210 // runtime mismatches.
13211 return GVA_Internal;
13212 }
13213
13214 return GVA_DiscardableODR;
13215}
13216
13218 const Decl *D, GVALinkage L) {
13219 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
13220 // dllexport/dllimport on inline functions.
13221 if (D->hasAttr<DLLImportAttr>()) {
13222 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
13224 } else if (D->hasAttr<DLLExportAttr>()) {
13225 if (L == GVA_DiscardableODR)
13226 return GVA_StrongODR;
13227 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) {
13228 // Device-side functions with __global__ attribute must always be
13229 // visible externally so they can be launched from host.
13230 if (D->hasAttr<CUDAGlobalAttr>() &&
13231 (L == GVA_DiscardableODR || L == GVA_Internal))
13232 return GVA_StrongODR;
13233 // Single source offloading languages like CUDA/HIP need to be able to
13234 // access static device variables from host code of the same compilation
13235 // unit. This is done by externalizing the static variable with a shared
13236 // name between the host and device compilation which is the same for the
13237 // same compilation unit whereas different among different compilation
13238 // units.
13239 if (Context.shouldExternalize(D))
13240 return GVA_StrongExternal;
13241 }
13242 return L;
13243}
13244
13245/// Adjust the GVALinkage for a declaration based on what an external AST source
13246/// knows about whether there can be other definitions of this declaration.
13247static GVALinkage
13249 GVALinkage L) {
13250 ExternalASTSource *Source = Ctx.getExternalSource();
13251 if (!Source)
13252 return L;
13253
13254 switch (Source->hasExternalDefinitions(D)) {
13256 // Other translation units rely on us to provide the definition.
13257 if (L == GVA_DiscardableODR)
13258 return GVA_StrongODR;
13259 break;
13260
13263
13265 break;
13266 }
13267 return L;
13268}
13269
13275
13277 const VarDecl *VD) {
13278 // As an extension for interactive REPLs, make sure constant variables are
13279 // only emitted once instead of LinkageComputer::getLVForNamespaceScopeDecl
13280 // marking them as internal.
13281 if (Context.getLangOpts().CPlusPlus &&
13282 Context.getLangOpts().IncrementalExtensions &&
13283 VD->getType().isConstQualified() &&
13284 !VD->getType().isVolatileQualified() && !VD->isInline() &&
13286 return GVA_DiscardableODR;
13287
13288 if (!VD->isExternallyVisible())
13289 return GVA_Internal;
13290
13291 if (VD->isStaticLocal()) {
13292 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
13293 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
13294 LexicalContext = LexicalContext->getLexicalParent();
13295
13296 // ObjC Blocks can create local variables that don't have a FunctionDecl
13297 // LexicalContext.
13298 if (!LexicalContext)
13299 return GVA_DiscardableODR;
13300
13301 // Otherwise, let the static local variable inherit its linkage from the
13302 // nearest enclosing function.
13303 auto StaticLocalLinkage =
13304 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
13305
13306 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
13307 // be emitted in any object with references to the symbol for the object it
13308 // contains, whether inline or out-of-line."
13309 // Similar behavior is observed with MSVC. An alternative ABI could use
13310 // StrongODR/AvailableExternally to match the function, but none are
13311 // known/supported currently.
13312 if (StaticLocalLinkage == GVA_StrongODR ||
13313 StaticLocalLinkage == GVA_AvailableExternally)
13314 return GVA_DiscardableODR;
13315 return StaticLocalLinkage;
13316 }
13317
13318 // MSVC treats in-class initialized static data members as definitions.
13319 // By giving them non-strong linkage, out-of-line definitions won't
13320 // cause link errors.
13321 if (Context.isMSStaticDataMemberInlineDefinition(VD))
13322 return GVA_DiscardableODR;
13323
13324 // Most non-template variables have strong linkage; inline variables are
13325 // linkonce_odr or (occasionally, for compatibility) weak_odr.
13326 GVALinkage StrongLinkage;
13327 switch (Context.getInlineVariableDefinitionKind(VD)) {
13329 StrongLinkage = GVA_StrongExternal;
13330 break;
13333 StrongLinkage = GVA_DiscardableODR;
13334 break;
13336 StrongLinkage = GVA_StrongODR;
13337 break;
13338 }
13339
13340 switch (VD->getTemplateSpecializationKind()) {
13341 case TSK_Undeclared:
13342 return StrongLinkage;
13343
13345 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13346 VD->isStaticDataMember()
13348 : StrongLinkage;
13349
13351 return GVA_StrongODR;
13352
13355
13357 return GVA_DiscardableODR;
13358 }
13359
13360 llvm_unreachable("Invalid Linkage!");
13361}
13362
13368
13370 if (const auto *VD = dyn_cast<VarDecl>(D)) {
13371 if (!VD->isFileVarDecl())
13372 return false;
13373 // Global named register variables (GNU extension) are never emitted.
13374 if (VD->getStorageClass() == SC_Register)
13375 return false;
13376 if (VD->getDescribedVarTemplate() ||
13378 return false;
13379 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
13380 // We never need to emit an uninstantiated function template.
13381 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
13382 return false;
13383 } else if (isa<PragmaCommentDecl>(D))
13384 return true;
13386 return true;
13387 else if (isa<OMPRequiresDecl>(D))
13388 return true;
13389 else if (isa<OMPThreadPrivateDecl>(D))
13390 return !D->getDeclContext()->isDependentContext();
13391 else if (isa<OMPAllocateDecl>(D))
13392 return !D->getDeclContext()->isDependentContext();
13394 return !D->getDeclContext()->isDependentContext();
13395 else if (isa<ImportDecl>(D))
13396 return true;
13397 else
13398 return false;
13399
13400 // If this is a member of a class template, we do not need to emit it.
13402 return false;
13403
13404 // Weak references don't produce any output by themselves.
13405 if (D->hasAttr<WeakRefAttr>())
13406 return false;
13407
13408 // SYCL device compilation requires that functions defined with the
13409 // sycl_kernel_entry_point or sycl_external attributes be emitted. All
13410 // other entities are emitted only if they are used by a function
13411 // defined with one of those attributes.
13412 if (LangOpts.SYCLIsDevice)
13413 return isa<FunctionDecl>(D) && (D->hasAttr<SYCLKernelEntryPointAttr>() ||
13414 D->hasAttr<SYCLExternalAttr>());
13415
13416 // Aliases and used decls are required.
13417 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
13418 return true;
13419
13420 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
13421 // Forward declarations aren't required.
13422 if (!FD->doesThisDeclarationHaveABody())
13423 return FD->doesDeclarationForceExternallyVisibleDefinition();
13424
13425 // Constructors and destructors are required.
13426 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
13427 return true;
13428
13429 // The key function for a class is required. This rule only comes
13430 // into play when inline functions can be key functions, though.
13431 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
13432 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
13433 const CXXRecordDecl *RD = MD->getParent();
13434 if (MD->isOutOfLine() && RD->isDynamicClass()) {
13435 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
13436 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
13437 return true;
13438 }
13439 }
13440 }
13441
13443
13444 // static, static inline, always_inline, and extern inline functions can
13445 // always be deferred. Normal inline functions can be deferred in C99/C++.
13446 // Implicit template instantiations can also be deferred in C++.
13448 }
13449
13450 const auto *VD = cast<VarDecl>(D);
13451 assert(VD->isFileVarDecl() && "Expected file scoped var");
13452
13453 // If the decl is marked as `declare target to`, it should be emitted for the
13454 // host and for the device.
13455 if (LangOpts.OpenMP &&
13456 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
13457 return true;
13458
13459 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
13461 return false;
13462
13463 if (VD->shouldEmitInExternalSource())
13464 return false;
13465
13466 // Variables that can be needed in other TUs are required.
13469 return true;
13470
13471 // We never need to emit a variable that is available in another TU.
13473 return false;
13474
13475 // Variables that have destruction with side-effects are required.
13476 if (VD->needsDestruction(*this))
13477 return true;
13478
13479 // Variables that have initialization with side-effects are required.
13480 if (VD->hasInitWithSideEffects())
13481 return true;
13482
13483 // Likewise, variables with tuple-like bindings are required if their
13484 // bindings have side-effects.
13485 if (const auto *DD = dyn_cast<DecompositionDecl>(VD)) {
13486 for (const auto *BD : DD->flat_bindings())
13487 if (const auto *BindingVD = BD->getHoldingVar())
13488 if (DeclMustBeEmitted(BindingVD))
13489 return true;
13490 }
13491
13492 return false;
13493}
13494
13495template <typename AttrT> static bool hasImplicitAttr(const ValueDecl *D) {
13496 if (auto *A = D->getAttr<AttrT>())
13497 return A->isImplicit();
13498 return D->isImplicit();
13499}
13500
13502 assert(LangOpts.CUDA && "Should not be called by non-CUDA languages");
13503 assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
13504 "Expected Variable or Function");
13505
13506 if (const auto *VD = dyn_cast<VarDecl>(D)) {
13507 // We need to emit host-side 'shadows' for all global device-side variables
13508 // because the CUDA runtime needs their size and host-side address in order
13509 // to provide access to their device-side incarnations.
13510 return !LangOpts.CUDAIsDevice || VD->hasAttr<CUDADeviceAttr>() ||
13511 VD->hasAttr<CUDAConstantAttr>() || VD->hasAttr<CUDASharedAttr>() ||
13512 VD->getType()->isCUDADeviceBuiltinSurfaceType() ||
13513 VD->getType()->isCUDADeviceBuiltinTextureType();
13514 }
13515
13516 const auto *FD = cast<FunctionDecl>(D);
13517 // Device-only functions are the only things we skip on the host.
13518 if (!LangOpts.CUDAIsDevice)
13519 return FD->hasAttr<CUDAHostAttr>() || !FD->hasAttr<CUDADeviceAttr>();
13520
13521 // Non-constexpr non-lambda implicit host device functions are not emitted
13522 // unless they are used on device side.
13523 return (FD->hasAttr<CUDADeviceAttr>() &&
13524 !(LangOpts.OffloadImplicitHostDeviceTemplates &&
13526 hasImplicitAttr<CUDADeviceAttr>(FD) && !FD->isConstexpr() &&
13527 !isLambdaCallOperator(FD) &&
13529 FD->hasAttr<CUDAGlobalAttr>() ||
13530 (LangOpts.HIPStdPar && !FD->hasAttr<CUDAHostAttr>());
13531}
13532
13534 const FunctionDecl *FD,
13535 llvm::function_ref<void(FunctionDecl *)> Pred) const {
13536 assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
13537 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
13538 FD = FD->getMostRecentDecl();
13539 // FIXME: The order of traversal here matters and depends on the order of
13540 // lookup results, which happens to be (mostly) oldest-to-newest, but we
13541 // shouldn't rely on that.
13542 for (auto *CurDecl :
13544 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
13545 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
13546 SeenDecls.insert(CurFD).second) {
13547 Pred(CurFD);
13548 }
13549 }
13550}
13551
13553 bool IsCXXMethod) const {
13554 // Pass through to the C++ ABI object
13555 if (IsCXXMethod)
13556 return ABI->getDefaultMethodCallConv(IsVariadic);
13557
13558 switch (LangOpts.getDefaultCallingConv()) {
13560 break;
13562 return CC_C;
13564 if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
13565 return CC_X86FastCall;
13566 break;
13568 if (!IsVariadic)
13569 return CC_X86StdCall;
13570 break;
13572 // __vectorcall cannot be applied to variadic functions.
13573 if (!IsVariadic)
13574 return CC_X86VectorCall;
13575 break;
13577 // __regcall cannot be applied to variadic functions.
13578 if (!IsVariadic)
13579 return CC_X86RegCall;
13580 break;
13582 if (!IsVariadic)
13583 return CC_M68kRTD;
13584 break;
13585 }
13586 return Target->getDefaultCallingConv();
13587}
13588
13590 // Pass through to the C++ ABI object
13591 return ABI->isNearlyEmpty(RD);
13592}
13593
13595 if (!VTContext) {
13596 auto ABI = Target->getCXXABI();
13597 if (ABI.isMicrosoft())
13598 VTContext.reset(new MicrosoftVTableContext(*this));
13599 else {
13600 VTContext.reset(new ItaniumVTableContext(*this));
13601 }
13602 }
13603 return VTContext.get();
13604}
13605
13607 if (!T)
13608 T = Target;
13609 switch (T->getCXXABI().getKind()) {
13610 case TargetCXXABI::AppleARM64:
13611 case TargetCXXABI::Fuchsia:
13612 case TargetCXXABI::GenericAArch64:
13613 case TargetCXXABI::GenericItanium:
13614 case TargetCXXABI::GenericARM:
13615 case TargetCXXABI::GenericMIPS:
13616 case TargetCXXABI::iOS:
13617 case TargetCXXABI::WebAssembly:
13618 case TargetCXXABI::WatchOS:
13619 case TargetCXXABI::XL:
13621 case TargetCXXABI::Microsoft:
13623 }
13624 llvm_unreachable("Unsupported ABI");
13625}
13626
13628 assert(T.getCXXABI().getKind() != TargetCXXABI::Microsoft &&
13629 "Device mangle context does not support Microsoft mangling.");
13630 switch (T.getCXXABI().getKind()) {
13631 case TargetCXXABI::AppleARM64:
13632 case TargetCXXABI::Fuchsia:
13633 case TargetCXXABI::GenericAArch64:
13634 case TargetCXXABI::GenericItanium:
13635 case TargetCXXABI::GenericARM:
13636 case TargetCXXABI::GenericMIPS:
13637 case TargetCXXABI::iOS:
13638 case TargetCXXABI::WebAssembly:
13639 case TargetCXXABI::WatchOS:
13640 case TargetCXXABI::XL:
13642 *this, getDiagnostics(),
13643 [](ASTContext &, const NamedDecl *ND) -> UnsignedOrNone {
13644 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
13645 return RD->getDeviceLambdaManglingNumber();
13646 return std::nullopt;
13647 },
13648 /*IsAux=*/true);
13649 case TargetCXXABI::Microsoft:
13651 /*IsAux=*/true);
13652 }
13653 llvm_unreachable("Unsupported ABI");
13654}
13655
13657 // If the host and device have different C++ ABIs, mark it as the device
13658 // mangle context so that the mangling needs to retrieve the additional
13659 // device lambda mangling number instead of the regular host one.
13660 if (getAuxTargetInfo() && getTargetInfo().getCXXABI().isMicrosoft() &&
13661 getAuxTargetInfo()->getCXXABI().isItaniumFamily()) {
13663 }
13664
13666}
13667
13668CXXABI::~CXXABI() = default;
13669
13671 return ASTRecordLayouts.getMemorySize() +
13672 llvm::capacity_in_bytes(ObjCLayouts) +
13673 llvm::capacity_in_bytes(KeyFunctions) +
13674 llvm::capacity_in_bytes(ObjCImpls) +
13675 llvm::capacity_in_bytes(BlockVarCopyInits) +
13676 DeclAttrAllocator.getTotalMemory() +
13677 llvm::capacity_in_bytes(TemplateOrInstantiation) +
13678 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
13679 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
13680 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
13681 llvm::capacity_in_bytes(OverriddenMethods) +
13682 llvm::capacity_in_bytes(Types) +
13683 llvm::capacity_in_bytes(VariableArrayTypes);
13684}
13685
13686/// getIntTypeForBitwidth -
13687/// sets integer QualTy according to specified details:
13688/// bitwidth, signed/unsigned.
13689/// Returns empty type if there is no appropriate target types.
13691 unsigned Signed) const {
13693 CanQualType QualTy = getFromTargetType(Ty);
13694 if (!QualTy && DestWidth == 128)
13695 return Signed ? Int128Ty : UnsignedInt128Ty;
13696 return QualTy;
13697}
13698
13700 unsigned Signed) const {
13701 return getFromTargetType(
13702 getTargetInfo().getLeastIntTypeByWidth(DestWidth, Signed));
13703}
13704
13705/// getRealTypeForBitwidth -
13706/// sets floating point QualTy according to specified bitwidth.
13707/// Returns empty type if there is no appropriate target types.
13709 FloatModeKind ExplicitType) const {
13710 FloatModeKind Ty =
13711 getTargetInfo().getRealTypeByWidth(DestWidth, ExplicitType);
13712 switch (Ty) {
13714 return HalfTy;
13716 return FloatTy;
13718 return DoubleTy;
13720 return LongDoubleTy;
13722 return Float128Ty;
13724 return Ibm128Ty;
13726 return {};
13727 }
13728
13729 llvm_unreachable("Unhandled TargetInfo::RealType value");
13730}
13731
13732void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
13733 if (Number <= 1)
13734 return;
13735
13736 MangleNumbers[ND] = Number;
13737
13738 if (Listener)
13739 Listener->AddedManglingNumber(ND, Number);
13740}
13741
13743 bool ForAuxTarget) const {
13744 auto I = MangleNumbers.find(ND);
13745 unsigned Res = I != MangleNumbers.end() ? I->second : 1;
13746 // CUDA/HIP host compilation encodes host and device mangling numbers
13747 // as lower and upper half of 32 bit integer.
13748 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice) {
13749 Res = ForAuxTarget ? Res >> 16 : Res & 0xFFFF;
13750 } else {
13751 assert(!ForAuxTarget && "Only CUDA/HIP host compilation supports mangling "
13752 "number for aux target");
13753 }
13754 return Res > 1 ? Res : 1;
13755}
13756
13757void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
13758 if (Number <= 1)
13759 return;
13760
13761 StaticLocalNumbers[VD] = Number;
13762
13763 if (Listener)
13764 Listener->AddedStaticLocalNumbers(VD, Number);
13765}
13766
13768 auto I = StaticLocalNumbers.find(VD);
13769 return I != StaticLocalNumbers.end() ? I->second : 1;
13770}
13771
13773 bool IsDestroying) {
13774 if (!IsDestroying) {
13775 assert(!DestroyingOperatorDeletes.contains(FD->getCanonicalDecl()));
13776 return;
13777 }
13778 DestroyingOperatorDeletes.insert(FD->getCanonicalDecl());
13779}
13780
13782 return DestroyingOperatorDeletes.contains(FD->getCanonicalDecl());
13783}
13784
13786 bool IsTypeAware) {
13787 if (!IsTypeAware) {
13788 assert(!TypeAwareOperatorNewAndDeletes.contains(FD->getCanonicalDecl()));
13789 return;
13790 }
13791 TypeAwareOperatorNewAndDeletes.insert(FD->getCanonicalDecl());
13792}
13793
13795 return TypeAwareOperatorNewAndDeletes.contains(FD->getCanonicalDecl());
13796}
13797
13799 FunctionDecl *OperatorDelete,
13800 OperatorDeleteKind K) const {
13801 switch (K) {
13803 OperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] = OperatorDelete;
13804 break;
13806 GlobalOperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] =
13807 OperatorDelete;
13808 break;
13810 ArrayOperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] =
13811 OperatorDelete;
13812 break;
13814 GlobalArrayOperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] =
13815 OperatorDelete;
13816 break;
13817 }
13818}
13819
13821 OperatorDeleteKind K) const {
13822 switch (K) {
13824 return OperatorDeletesForVirtualDtor.contains(Dtor->getCanonicalDecl());
13826 return GlobalOperatorDeletesForVirtualDtor.contains(
13827 Dtor->getCanonicalDecl());
13829 return ArrayOperatorDeletesForVirtualDtor.contains(
13830 Dtor->getCanonicalDecl());
13832 return GlobalArrayOperatorDeletesForVirtualDtor.contains(
13833 Dtor->getCanonicalDecl());
13834 }
13835 return false;
13836}
13837
13840 OperatorDeleteKind K) const {
13841 const CXXDestructorDecl *Canon = Dtor->getCanonicalDecl();
13842 switch (K) {
13844 if (OperatorDeletesForVirtualDtor.contains(Canon))
13845 return OperatorDeletesForVirtualDtor[Canon];
13846 return nullptr;
13848 if (GlobalOperatorDeletesForVirtualDtor.contains(Canon))
13849 return GlobalOperatorDeletesForVirtualDtor[Canon];
13850 return nullptr;
13852 if (ArrayOperatorDeletesForVirtualDtor.contains(Canon))
13853 return ArrayOperatorDeletesForVirtualDtor[Canon];
13854 return nullptr;
13856 if (GlobalArrayOperatorDeletesForVirtualDtor.contains(Canon))
13857 return GlobalArrayOperatorDeletesForVirtualDtor[Canon];
13858 return nullptr;
13859 }
13860 return nullptr;
13861}
13862
13864 const CXXRecordDecl *RD) {
13865 if (!getTargetInfo().emitVectorDeletingDtors(getLangOpts()))
13866 return false;
13867
13868 return MaybeRequireVectorDeletingDtor.count(RD);
13869}
13870
13872 const CXXRecordDecl *RD) {
13873 if (!getTargetInfo().emitVectorDeletingDtors(getLangOpts()))
13874 return;
13875
13876 MaybeRequireVectorDeletingDtor.insert(RD);
13877}
13878
13881 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13882 // Reopened namespaces share a mangling context so that declarations in
13883 // different namespace blocks do not receive duplicate mangling numbers.
13884 DC = DC->getPrimaryContext();
13885 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
13886 if (!MCtx)
13888 return *MCtx;
13889}
13890
13893 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13894 std::unique_ptr<MangleNumberingContext> &MCtx =
13895 ExtraMangleNumberingContexts[D];
13896 if (!MCtx)
13898 return *MCtx;
13899}
13900
13901std::unique_ptr<MangleNumberingContext>
13903 return ABI->createMangleNumberingContext();
13904}
13905
13906const CXXConstructorDecl *
13908 return ABI->getCopyConstructorForExceptionObject(
13910}
13911
13913 CXXConstructorDecl *CD) {
13914 return ABI->addCopyConstructorForExceptionObject(
13917}
13918
13920 TypedefNameDecl *DD) {
13921 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
13922}
13923
13926 return ABI->getTypedefNameForUnnamedTagDecl(TD);
13927}
13928
13930 DeclaratorDecl *DD) {
13931 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
13932}
13933
13935 return ABI->getDeclaratorForUnnamedTagDecl(TD);
13936}
13937
13939 ParamIndices[D] = index;
13940}
13941
13943 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
13944 assert(I != ParamIndices.end() &&
13945 "ParmIndices lacks entry set by ParmVarDecl");
13946 return I->second;
13947}
13948
13950 unsigned Length) const {
13951 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
13952 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
13953 EltTy = EltTy.withConst();
13954
13955 EltTy = adjustStringLiteralBaseType(EltTy);
13956
13957 // Get an array type for the string, according to C99 6.4.5. This includes
13958 // the null terminator character.
13959 return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr,
13960 ArraySizeModifier::Normal, /*IndexTypeQuals*/ 0);
13961}
13962
13965 StringLiteral *&Result = StringLiteralCache[Key];
13966 if (!Result)
13968 *this, Key, StringLiteralKind::Ordinary,
13969 /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()),
13970 SourceLocation());
13971 return Result;
13972}
13973
13974MSGuidDecl *
13976 assert(MSGuidTagDecl && "building MS GUID without MS extensions?");
13977
13978 llvm::FoldingSetNodeID ID;
13979 MSGuidDecl::Profile(ID, Parts);
13980
13981 llvm::FoldingSetInsertToken Token;
13982 if (MSGuidDecl *Existing = MSGuidDecls.lookup(ID, Token))
13983 return Existing;
13984
13985 QualType GUIDType = getMSGuidType().withConst();
13986 MSGuidDecl *New = MSGuidDecl::Create(*this, GUIDType, Parts);
13987 MSGuidDecls.insert(New, Token);
13988 return New;
13989}
13990
13993 const APValue &APVal) const {
13994 llvm::FoldingSetNodeID ID;
13996
13997 llvm::FoldingSetInsertToken Token;
13998 if (UnnamedGlobalConstantDecl *Existing =
13999 UnnamedGlobalConstantDecls.lookup(ID, Token))
14000 return Existing;
14001
14003 UnnamedGlobalConstantDecl::Create(*this, Ty, APVal);
14004 UnnamedGlobalConstantDecls.insert(New, Token);
14005 return New;
14006}
14007
14010 assert(T->isRecordType() && "template param object of unexpected type");
14011
14012 // C++ [temp.param]p8:
14013 // [...] a static storage duration object of type 'const T' [...]
14014 T.addConst();
14015
14016 llvm::FoldingSetNodeID ID;
14018
14019 llvm::FoldingSetInsertToken Token;
14020 if (TemplateParamObjectDecl *Existing =
14021 TemplateParamObjectDecls.lookup(ID, Token))
14022 return Existing;
14023
14024 TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(*this, T, V);
14025 TemplateParamObjectDecls.insert(New, Token);
14026 return New;
14027}
14028
14030 const llvm::Triple &T = getTargetInfo().getTriple();
14031 if (!T.isOSDarwin())
14032 return false;
14033
14034 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
14035 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
14036 return false;
14037
14038 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
14039 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
14040 uint64_t Size = sizeChars.getQuantity();
14041 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
14042 unsigned Align = alignChars.getQuantity();
14043 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
14044 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
14045}
14046
14047bool
14049 const ObjCMethodDecl *MethodImpl) {
14050 // No point trying to match an unavailable/deprecated mothod.
14051 if (MethodDecl->hasAttr<UnavailableAttr>()
14052 || MethodDecl->hasAttr<DeprecatedAttr>())
14053 return false;
14054 if (MethodDecl->getObjCDeclQualifier() !=
14055 MethodImpl->getObjCDeclQualifier())
14056 return false;
14057 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
14058 return false;
14059
14060 if (MethodDecl->param_size() != MethodImpl->param_size())
14061 return false;
14062
14063 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
14064 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
14065 EF = MethodDecl->param_end();
14066 IM != EM && IF != EF; ++IM, ++IF) {
14067 const ParmVarDecl *DeclVar = (*IF);
14068 const ParmVarDecl *ImplVar = (*IM);
14069 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
14070 return false;
14071 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
14072 return false;
14073 }
14074
14075 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
14076}
14077
14079 LangAS AS;
14081 AS = LangAS::Default;
14082 else
14083 AS = QT->getPointeeType().getAddressSpace();
14084
14086}
14087
14090}
14091
14092bool ASTContext::hasSameExpr(const Expr *X, const Expr *Y) const {
14093 if (X == Y)
14094 return true;
14095 if (!X || !Y)
14096 return false;
14097 llvm::FoldingSetNodeID IDX, IDY;
14098 X->Profile(IDX, *this, /*Canonical=*/true);
14099 Y->Profile(IDY, *this, /*Canonical=*/true);
14100 return IDX == IDY;
14101}
14102
14103// The getCommon* helpers return, for given 'same' X and Y entities given as
14104// inputs, another entity which is also the 'same' as the inputs, but which
14105// is closer to the canonical form of the inputs, each according to a given
14106// criteria.
14107// The getCommon*Checked variants are 'null inputs not-allowed' equivalents of
14108// the regular ones.
14109
14111 if (!declaresSameEntity(X, Y))
14112 return nullptr;
14113 for (const Decl *DX : X->redecls()) {
14114 // If we reach Y before reaching the first decl, that means X is older.
14115 if (DX == Y)
14116 return X;
14117 // If we reach the first decl, then Y is older.
14118 if (DX->isFirstDecl())
14119 return Y;
14120 }
14121 llvm_unreachable("Corrupt redecls chain");
14122}
14123
14124template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
14125static T *getCommonDecl(T *X, T *Y) {
14126 return cast_or_null<T>(
14127 getCommonDecl(const_cast<Decl *>(cast_or_null<Decl>(X)),
14128 const_cast<Decl *>(cast_or_null<Decl>(Y))));
14129}
14130
14131template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
14132static T *getCommonDeclChecked(T *X, T *Y) {
14133 return cast<T>(getCommonDecl(const_cast<Decl *>(cast<Decl>(X)),
14134 const_cast<Decl *>(cast<Decl>(Y))));
14135}
14136
14138 TemplateName Y,
14139 bool IgnoreDeduced = false) {
14140 if (X.getAsVoidPointer() == Y.getAsVoidPointer())
14141 return X;
14142 // FIXME: There are cases here where we could find a common template name
14143 // with more sugar. For example one could be a SubstTemplateTemplate*
14144 // replacing the other.
14145 TemplateName CX = Ctx.getCanonicalTemplateName(X, IgnoreDeduced);
14146 if (CX.getAsVoidPointer() !=
14148 return TemplateName();
14149 return CX;
14150}
14151
14154 bool IgnoreDeduced) {
14155 TemplateName R = getCommonTemplateName(Ctx, X, Y, IgnoreDeduced);
14156 assert(R.getAsVoidPointer() != nullptr);
14157 return R;
14158}
14159
14161 ArrayRef<QualType> Ys, bool Unqualified = false) {
14162 assert(Xs.size() == Ys.size());
14163 SmallVector<QualType, 8> Rs(Xs.size());
14164 for (size_t I = 0; I < Rs.size(); ++I)
14165 Rs[I] = Ctx.getCommonSugaredType(Xs[I], Ys[I], Unqualified);
14166 return Rs;
14167}
14168
14169template <class T>
14170static SourceLocation getCommonAttrLoc(const T *X, const T *Y) {
14171 return X->getAttributeLoc() == Y->getAttributeLoc() ? X->getAttributeLoc()
14172 : SourceLocation();
14173}
14174
14176 const TemplateArgument &X,
14177 const TemplateArgument &Y) {
14178 if (X.getKind() != Y.getKind())
14179 return TemplateArgument();
14180
14181 switch (X.getKind()) {
14183 if (!Ctx.hasSameType(X.getAsType(), Y.getAsType()))
14184 return TemplateArgument();
14185 return TemplateArgument(
14186 Ctx.getCommonSugaredType(X.getAsType(), Y.getAsType()));
14188 if (!Ctx.hasSameType(X.getNullPtrType(), Y.getNullPtrType()))
14189 return TemplateArgument();
14190 return TemplateArgument(
14191 Ctx.getCommonSugaredType(X.getNullPtrType(), Y.getNullPtrType()),
14192 /*Unqualified=*/true);
14194 if (!Ctx.hasSameType(X.getAsExpr()->getType(), Y.getAsExpr()->getType()))
14195 return TemplateArgument();
14196 // FIXME: Try to keep the common sugar.
14197 return X;
14199 TemplateName TX = X.getAsTemplate(), TY = Y.getAsTemplate();
14200 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
14201 if (!CTN.getAsVoidPointer())
14202 return TemplateArgument();
14203 return TemplateArgument(CTN);
14204 }
14206 TemplateName TX = X.getAsTemplateOrTemplatePattern(),
14208 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
14209 if (!CTN.getAsVoidPointer())
14210 return TemplateName();
14211 auto NExpX = X.getNumTemplateExpansions();
14212 assert(NExpX == Y.getNumTemplateExpansions());
14213 return TemplateArgument(CTN, NExpX);
14214 }
14215 default:
14216 // FIXME: Handle the other argument kinds.
14217 return X;
14218 }
14219}
14220
14225 if (Xs.size() != Ys.size())
14226 return true;
14227 R.resize(Xs.size());
14228 for (size_t I = 0; I < R.size(); ++I) {
14229 R[I] = getCommonTemplateArgument(Ctx, Xs[I], Ys[I]);
14230 if (R[I].isNull())
14231 return true;
14232 }
14233 return false;
14234}
14235
14240 bool Different = getCommonTemplateArguments(Ctx, R, Xs, Ys);
14241 assert(!Different);
14242 (void)Different;
14243 return R;
14244}
14245
14246template <class T>
14248 bool IsSame) {
14249 ElaboratedTypeKeyword KX = X->getKeyword(), KY = Y->getKeyword();
14250 if (KX == KY)
14251 return KX;
14253 assert(!IsSame || KX == getCanonicalElaboratedTypeKeyword(KY));
14254 return KX;
14255}
14256
14257/// Returns a NestedNameSpecifier which has only the common sugar
14258/// present in both NNS1 and NNS2.
14261 NestedNameSpecifier NNS2, bool IsSame) {
14262 // If they are identical, all sugar is common.
14263 if (NNS1 == NNS2)
14264 return NNS1;
14265
14266 // IsSame implies both Qualifiers are equivalent.
14267 NestedNameSpecifier Canon = NNS1.getCanonical();
14268 if (Canon != NNS2.getCanonical()) {
14269 assert(!IsSame && "Should be the same NestedNameSpecifier");
14270 // If they are not the same, there is nothing to unify.
14271 return std::nullopt;
14272 }
14273
14274 NestedNameSpecifier R = std::nullopt;
14275 NestedNameSpecifier::Kind Kind = NNS1.getKind();
14276 assert(Kind == NNS2.getKind());
14277 switch (Kind) {
14279 auto [Namespace1, Prefix1] = NNS1.getAsNamespaceAndPrefix();
14280 auto [Namespace2, Prefix2] = NNS2.getAsNamespaceAndPrefix();
14281 auto Kind = Namespace1->getKind();
14282 if (Kind != Namespace2->getKind() ||
14283 (Kind == Decl::NamespaceAlias &&
14284 !declaresSameEntity(Namespace1, Namespace2))) {
14286 Ctx,
14287 ::getCommonDeclChecked(Namespace1->getNamespace(),
14288 Namespace2->getNamespace()),
14289 /*Prefix=*/std::nullopt);
14290 break;
14291 }
14292 // The prefixes for namespaces are not significant, its declaration
14293 // identifies it uniquely.
14294 NestedNameSpecifier Prefix = ::getCommonNNS(Ctx, Prefix1, Prefix2,
14295 /*IsSame=*/false);
14296 R = NestedNameSpecifier(Ctx, ::getCommonDeclChecked(Namespace1, Namespace2),
14297 Prefix);
14298 break;
14299 }
14301 const Type *T1 = NNS1.getAsType(), *T2 = NNS2.getAsType();
14302 const Type *T = Ctx.getCommonSugaredType(QualType(T1, 0), QualType(T2, 0),
14303 /*Unqualified=*/true)
14304 .getTypePtr();
14306 break;
14307 }
14309 // FIXME: Can __super even be used with data members?
14310 // If it's only usable in functions, we will never see it here,
14311 // unless we save the qualifiers used in function types.
14312 // In that case, it might be possible NNS2 is a type,
14313 // in which case we should degrade the result to
14314 // a CXXRecordType.
14316 NNS2.getAsMicrosoftSuper()));
14317 break;
14318 }
14321 // These are singletons.
14322 llvm_unreachable("singletons did not compare equal");
14323 }
14324 assert(R.getCanonical() == Canon);
14325 return R;
14326}
14327
14328template <class T>
14330 const T *Y, bool IsSame) {
14331 return ::getCommonNNS(Ctx, X->getQualifier(), Y->getQualifier(), IsSame);
14332}
14333
14334template <class T>
14335static QualType getCommonElementType(const ASTContext &Ctx, const T *X,
14336 const T *Y) {
14337 return Ctx.getCommonSugaredType(X->getElementType(), Y->getElementType());
14338}
14339
14341 QualType X, QualType Y,
14342 Qualifiers &QX,
14343 Qualifiers &QY) {
14344 QualType R = Ctx.getCommonSugaredType(X, Y,
14345 /*Unqualified=*/true);
14346 // Qualifiers common to both element types.
14347 Qualifiers RQ = R.getQualifiers();
14348 // For each side, move to the top level any qualifiers which are not common to
14349 // both element types. The caller must assume top level qualifiers might
14350 // be different, even if they are the same type, and can be treated as sugar.
14351 QX += X.getQualifiers() - RQ;
14352 QY += Y.getQualifiers() - RQ;
14353 return R;
14354}
14355
14356template <class T>
14358 Qualifiers &QX, const T *Y,
14359 Qualifiers &QY) {
14360 return getCommonTypeWithQualifierLifting(Ctx, X->getElementType(),
14361 Y->getElementType(), QX, QY);
14362}
14363
14364template <class T>
14365static QualType getCommonPointeeType(const ASTContext &Ctx, const T *X,
14366 const T *Y) {
14367 return Ctx.getCommonSugaredType(X->getPointeeType(), Y->getPointeeType());
14368}
14369
14370template <class T>
14371static auto *getCommonSizeExpr(const ASTContext &Ctx, T *X, T *Y) {
14372 assert(Ctx.hasSameExpr(X->getSizeExpr(), Y->getSizeExpr()));
14373 return X->getSizeExpr();
14374}
14375
14376static auto getCommonSizeModifier(const ArrayType *X, const ArrayType *Y) {
14377 assert(X->getSizeModifier() == Y->getSizeModifier());
14378 return X->getSizeModifier();
14379}
14380
14382 const ArrayType *Y) {
14383 assert(X->getIndexTypeCVRQualifiers() == Y->getIndexTypeCVRQualifiers());
14384 return X->getIndexTypeCVRQualifiers();
14385}
14386
14387// Merges two type lists such that the resulting vector will contain
14388// each type (in a canonical sense) only once, in the order they appear
14389// from X to Y. If they occur in both X and Y, the result will contain
14390// the common sugared type between them.
14391static void mergeTypeLists(const ASTContext &Ctx,
14394 llvm::DenseMap<QualType, unsigned> Found;
14395 for (auto Ts : {X, Y}) {
14396 for (QualType T : Ts) {
14397 auto Res = Found.try_emplace(Ctx.getCanonicalType(T), Out.size());
14398 if (!Res.second) {
14399 QualType &U = Out[Res.first->second];
14400 U = Ctx.getCommonSugaredType(U, T);
14401 } else {
14402 Out.emplace_back(T);
14403 }
14404 }
14405 }
14406}
14407
14408FunctionProtoType::ExceptionSpecInfo
14411 SmallVectorImpl<QualType> &ExceptionTypeStorage,
14412 bool AcceptDependent) const {
14413 ExceptionSpecificationType EST1 = ESI1.Type, EST2 = ESI2.Type;
14414
14415 // If either of them can throw anything, that is the result.
14416 for (auto I : {EST_None, EST_MSAny, EST_NoexceptFalse}) {
14417 if (EST1 == I)
14418 return ESI1;
14419 if (EST2 == I)
14420 return ESI2;
14421 }
14422
14423 // If either of them is non-throwing, the result is the other.
14424 for (auto I :
14426 if (EST1 == I)
14427 return ESI2;
14428 if (EST2 == I)
14429 return ESI1;
14430 }
14431
14432 // If we're left with value-dependent computed noexcept expressions, we're
14433 // stuck. Before C++17, we can just drop the exception specification entirely,
14434 // since it's not actually part of the canonical type. And this should never
14435 // happen in C++17, because it would mean we were computing the composite
14436 // pointer type of dependent types, which should never happen.
14437 if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) {
14438 assert(AcceptDependent &&
14439 "computing composite pointer type of dependent types");
14441 }
14442
14443 // Switch over the possibilities so that people adding new values know to
14444 // update this function.
14445 switch (EST1) {
14446 case EST_None:
14447 case EST_DynamicNone:
14448 case EST_MSAny:
14449 case EST_BasicNoexcept:
14451 case EST_NoexceptFalse:
14452 case EST_NoexceptTrue:
14453 case EST_NoThrow:
14454 llvm_unreachable("These ESTs should be handled above");
14455
14456 case EST_Dynamic: {
14457 // This is the fun case: both exception specifications are dynamic. Form
14458 // the union of the two lists.
14459 assert(EST2 == EST_Dynamic && "other cases should already be handled");
14460 mergeTypeLists(*this, ExceptionTypeStorage, ESI1.Exceptions,
14461 ESI2.Exceptions);
14463 Result.Exceptions = ExceptionTypeStorage;
14464 return Result;
14465 }
14466
14467 case EST_Unevaluated:
14468 case EST_Uninstantiated:
14469 case EST_Unparsed:
14470 llvm_unreachable("shouldn't see unresolved exception specifications here");
14471 }
14472
14473 llvm_unreachable("invalid ExceptionSpecificationType");
14474}
14475
14477 Qualifiers &QX, const Type *Y,
14478 Qualifiers &QY) {
14479 Type::TypeClass TC = X->getTypeClass();
14480 assert(TC == Y->getTypeClass());
14481 switch (TC) {
14482#define UNEXPECTED_TYPE(Class, Kind) \
14483 case Type::Class: \
14484 llvm_unreachable("Unexpected " Kind ": " #Class);
14485
14486#define NON_CANONICAL_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "non-canonical")
14487#define TYPE(Class, Base)
14488#include "clang/AST/TypeNodes.inc"
14489
14490#define SUGAR_FREE_TYPE(Class) UNEXPECTED_TYPE(Class, "sugar-free")
14492 SUGAR_FREE_TYPE(DeducedTemplateSpecialization)
14493 SUGAR_FREE_TYPE(DependentBitInt)
14495 SUGAR_FREE_TYPE(ObjCInterface)
14496 SUGAR_FREE_TYPE(SubstTemplateTypeParmPack)
14497 SUGAR_FREE_TYPE(SubstBuiltinTemplatePack)
14498 SUGAR_FREE_TYPE(UnresolvedUsing)
14499 SUGAR_FREE_TYPE(HLSLAttributedResource)
14500 SUGAR_FREE_TYPE(HLSLInlineSpirv)
14501#undef SUGAR_FREE_TYPE
14502#define NON_UNIQUE_TYPE(Class) UNEXPECTED_TYPE(Class, "non-unique")
14503 NON_UNIQUE_TYPE(TypeOfExpr)
14504 NON_UNIQUE_TYPE(VariableArray)
14505#undef NON_UNIQUE_TYPE
14506
14507 UNEXPECTED_TYPE(TypeOf, "sugar")
14508
14509#undef UNEXPECTED_TYPE
14510
14511 case Type::Auto: {
14512 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
14513 assert(AX->getDeducedKind() == AY->getDeducedKind());
14514 assert(AX->getDeducedKind() != DeducedKind::Deduced);
14515 assert(AX->getKeyword() == AY->getKeyword());
14516 TemplateDecl *CD =
14517 ::getCommonDecl(AX->getTypeConstraintConcept().getAsTemplateDecl(),
14518 AY->getTypeConstraintConcept().getAsTemplateDecl());
14520 if (CD &&
14521 getCommonTemplateArguments(Ctx, As, AX->getTypeConstraintArguments(),
14522 AY->getTypeConstraintArguments())) {
14523 CD = nullptr; // The arguments differ, so make it unconstrained.
14524 As.clear();
14525 }
14526 return Ctx.getAutoType(AX->getDeducedKind(), QualType(), AX->getKeyword(),
14527 TemplateName(CD), As);
14528 }
14529 case Type::IncompleteArray: {
14530 const auto *AX = cast<IncompleteArrayType>(X),
14532 return Ctx.getIncompleteArrayType(
14533 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
14535 }
14536 case Type::DependentSizedArray: {
14537 const auto *AX = cast<DependentSizedArrayType>(X),
14539 return Ctx.getDependentSizedArrayType(
14540 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
14541 getCommonSizeExpr(Ctx, AX, AY), getCommonSizeModifier(AX, AY),
14543 }
14544 case Type::ConstantArray: {
14545 const auto *AX = cast<ConstantArrayType>(X),
14546 *AY = cast<ConstantArrayType>(Y);
14547 assert(AX->getSize() == AY->getSize());
14548 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
14549 ? AX->getSizeExpr()
14550 : nullptr;
14551 return Ctx.getConstantArrayType(
14552 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
14554 }
14555 case Type::ArrayParameter: {
14556 const auto *AX = cast<ArrayParameterType>(X),
14557 *AY = cast<ArrayParameterType>(Y);
14558 assert(AX->getSize() == AY->getSize());
14559 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
14560 ? AX->getSizeExpr()
14561 : nullptr;
14562 auto ArrayTy = Ctx.getConstantArrayType(
14563 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
14565 return Ctx.getArrayParameterType(ArrayTy);
14566 }
14567 case Type::Atomic: {
14568 const auto *AX = cast<AtomicType>(X), *AY = cast<AtomicType>(Y);
14569 return Ctx.getAtomicType(
14570 Ctx.getCommonSugaredType(AX->getValueType(), AY->getValueType()));
14571 }
14572 case Type::Complex: {
14573 const auto *CX = cast<ComplexType>(X), *CY = cast<ComplexType>(Y);
14574 return Ctx.getComplexType(getCommonArrayElementType(Ctx, CX, QX, CY, QY));
14575 }
14576 case Type::Pointer: {
14577 const auto *PX = cast<PointerType>(X), *PY = cast<PointerType>(Y);
14578 return Ctx.getPointerType(getCommonPointeeType(Ctx, PX, PY));
14579 }
14580 case Type::BlockPointer: {
14581 const auto *PX = cast<BlockPointerType>(X), *PY = cast<BlockPointerType>(Y);
14582 return Ctx.getBlockPointerType(getCommonPointeeType(Ctx, PX, PY));
14583 }
14584 case Type::ObjCObjectPointer: {
14585 const auto *PX = cast<ObjCObjectPointerType>(X),
14587 return Ctx.getObjCObjectPointerType(getCommonPointeeType(Ctx, PX, PY));
14588 }
14589 case Type::MemberPointer: {
14590 const auto *PX = cast<MemberPointerType>(X),
14591 *PY = cast<MemberPointerType>(Y);
14592 assert(declaresSameEntity(PX->getMostRecentCXXRecordDecl(),
14593 PY->getMostRecentCXXRecordDecl()));
14594 return Ctx.getMemberPointerType(
14595 getCommonPointeeType(Ctx, PX, PY),
14596 getCommonQualifier(Ctx, PX, PY, /*IsSame=*/true),
14597 PX->getMostRecentCXXRecordDecl());
14598 }
14599 case Type::LValueReference: {
14600 const auto *PX = cast<LValueReferenceType>(X),
14602 // FIXME: Preserve PointeeTypeAsWritten.
14603 return Ctx.getLValueReferenceType(getCommonPointeeType(Ctx, PX, PY),
14604 PX->isSpelledAsLValue() ||
14605 PY->isSpelledAsLValue());
14606 }
14607 case Type::RValueReference: {
14608 const auto *PX = cast<RValueReferenceType>(X),
14610 // FIXME: Preserve PointeeTypeAsWritten.
14611 return Ctx.getRValueReferenceType(getCommonPointeeType(Ctx, PX, PY));
14612 }
14613 case Type::DependentAddressSpace: {
14614 const auto *PX = cast<DependentAddressSpaceType>(X),
14616 assert(Ctx.hasSameExpr(PX->getAddrSpaceExpr(), PY->getAddrSpaceExpr()));
14617 return Ctx.getDependentAddressSpaceType(getCommonPointeeType(Ctx, PX, PY),
14618 PX->getAddrSpaceExpr(),
14619 getCommonAttrLoc(PX, PY));
14620 }
14621 case Type::FunctionNoProto: {
14622 const auto *FX = cast<FunctionNoProtoType>(X),
14624 assert(FX->getExtInfo() == FY->getExtInfo());
14625 return Ctx.getFunctionNoProtoType(
14626 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType()),
14627 FX->getExtInfo());
14628 }
14629 case Type::FunctionProto: {
14630 const auto *FX = cast<FunctionProtoType>(X),
14631 *FY = cast<FunctionProtoType>(Y);
14632 FunctionProtoType::ExtProtoInfo EPIX = FX->getExtProtoInfo(),
14633 EPIY = FY->getExtProtoInfo();
14634 assert(EPIX.ExtInfo == EPIY.ExtInfo);
14635 assert(!EPIX.ExtParameterInfos == !EPIY.ExtParameterInfos);
14636 assert(!EPIX.ExtParameterInfos ||
14637 llvm::equal(
14638 llvm::ArrayRef(EPIX.ExtParameterInfos, FX->getNumParams()),
14639 llvm::ArrayRef(EPIY.ExtParameterInfos, FY->getNumParams())));
14640 assert(EPIX.RefQualifier == EPIY.RefQualifier);
14641 assert(EPIX.TypeQuals == EPIY.TypeQuals);
14642 assert(EPIX.Variadic == EPIY.Variadic);
14643
14644 // FIXME: Can we handle an empty EllipsisLoc?
14645 // Use emtpy EllipsisLoc if X and Y differ.
14646
14647 EPIX.HasTrailingReturn = EPIX.HasTrailingReturn && EPIY.HasTrailingReturn;
14648
14649 QualType R =
14650 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType());
14651 auto P = getCommonTypes(Ctx, FX->param_types(), FY->param_types(),
14652 /*Unqualified=*/true);
14653
14654 SmallVector<QualType, 8> Exceptions;
14656 EPIX.ExceptionSpec, EPIY.ExceptionSpec, Exceptions, true);
14657 return Ctx.getFunctionType(R, P, EPIX);
14658 }
14659 case Type::ObjCObject: {
14660 const auto *OX = cast<ObjCObjectType>(X), *OY = cast<ObjCObjectType>(Y);
14661 assert(
14662 std::equal(OX->getProtocols().begin(), OX->getProtocols().end(),
14663 OY->getProtocols().begin(), OY->getProtocols().end(),
14664 [](const ObjCProtocolDecl *P0, const ObjCProtocolDecl *P1) {
14665 return P0->getCanonicalDecl() == P1->getCanonicalDecl();
14666 }) &&
14667 "protocol lists must be the same");
14668 auto TAs = getCommonTypes(Ctx, OX->getTypeArgsAsWritten(),
14669 OY->getTypeArgsAsWritten());
14670 return Ctx.getObjCObjectType(
14671 Ctx.getCommonSugaredType(OX->getBaseType(), OY->getBaseType()), TAs,
14672 OX->getProtocols(),
14673 OX->isKindOfTypeAsWritten() && OY->isKindOfTypeAsWritten());
14674 }
14675 case Type::ConstantMatrix: {
14676 const auto *MX = cast<ConstantMatrixType>(X),
14677 *MY = cast<ConstantMatrixType>(Y);
14678 assert(MX->getNumRows() == MY->getNumRows());
14679 assert(MX->getNumColumns() == MY->getNumColumns());
14680 return Ctx.getConstantMatrixType(getCommonElementType(Ctx, MX, MY),
14681 MX->getNumRows(), MX->getNumColumns());
14682 }
14683 case Type::DependentSizedMatrix: {
14684 const auto *MX = cast<DependentSizedMatrixType>(X),
14686 assert(Ctx.hasSameExpr(MX->getRowExpr(), MY->getRowExpr()));
14687 assert(Ctx.hasSameExpr(MX->getColumnExpr(), MY->getColumnExpr()));
14688 return Ctx.getDependentSizedMatrixType(
14689 getCommonElementType(Ctx, MX, MY), MX->getRowExpr(),
14690 MX->getColumnExpr(), getCommonAttrLoc(MX, MY));
14691 }
14692 case Type::Vector: {
14693 const auto *VX = cast<VectorType>(X), *VY = cast<VectorType>(Y);
14694 assert(VX->getNumElements() == VY->getNumElements());
14695 assert(VX->getVectorKind() == VY->getVectorKind());
14696 return Ctx.getVectorType(getCommonElementType(Ctx, VX, VY),
14697 VX->getNumElements(), VX->getVectorKind());
14698 }
14699 case Type::ExtVector: {
14700 const auto *VX = cast<ExtVectorType>(X), *VY = cast<ExtVectorType>(Y);
14701 assert(VX->getNumElements() == VY->getNumElements());
14702 return Ctx.getExtVectorType(getCommonElementType(Ctx, VX, VY),
14703 VX->getNumElements());
14704 }
14705 case Type::DependentSizedExtVector: {
14706 const auto *VX = cast<DependentSizedExtVectorType>(X),
14709 getCommonSizeExpr(Ctx, VX, VY),
14710 getCommonAttrLoc(VX, VY));
14711 }
14712 case Type::DependentVector: {
14713 const auto *VX = cast<DependentVectorType>(X),
14715 assert(VX->getVectorKind() == VY->getVectorKind());
14716 return Ctx.getDependentVectorType(
14717 getCommonElementType(Ctx, VX, VY), getCommonSizeExpr(Ctx, VX, VY),
14718 getCommonAttrLoc(VX, VY), VX->getVectorKind());
14719 }
14720 case Type::Enum:
14721 case Type::Record:
14722 case Type::InjectedClassName: {
14723 const auto *TX = cast<TagType>(X), *TY = cast<TagType>(Y);
14724 return Ctx.getTagType(::getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14725 ::getCommonQualifier(Ctx, TX, TY, /*IsSame=*/false),
14726 ::getCommonDeclChecked(TX->getDecl(), TY->getDecl()),
14727 /*OwnedTag=*/false);
14728 }
14729 case Type::TemplateSpecialization: {
14730 const auto *TX = cast<TemplateSpecializationType>(X),
14732 auto As = getCommonTemplateArguments(Ctx, TX->template_arguments(),
14733 TY->template_arguments());
14735 getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14736 ::getCommonTemplateNameChecked(Ctx, TX->getTemplateName(),
14737 TY->getTemplateName(),
14738 /*IgnoreDeduced=*/true),
14739 As, /*CanonicalArgs=*/{}, X->getCanonicalTypeInternal());
14740 }
14741 case Type::Decltype: {
14742 const auto *DX = cast<DecltypeType>(X);
14743 [[maybe_unused]] const auto *DY = cast<DecltypeType>(Y);
14744 assert(DX->isDependentType());
14745 assert(DY->isDependentType());
14746 assert(Ctx.hasSameExpr(DX->getUnderlyingExpr(), DY->getUnderlyingExpr()));
14747 // As Decltype is not uniqued, building a common type would be wasteful.
14748 return QualType(DX, 0);
14749 }
14750 case Type::PackIndexing: {
14751 const auto *DX = cast<PackIndexingType>(X);
14752 [[maybe_unused]] const auto *DY = cast<PackIndexingType>(Y);
14753 assert(DX->isDependentType());
14754 assert(DY->isDependentType());
14755 assert(Ctx.hasSameExpr(DX->getIndexExpr(), DY->getIndexExpr()));
14756 return QualType(DX, 0);
14757 }
14758 case Type::DependentName: {
14759 const auto *NX = cast<DependentNameType>(X),
14760 *NY = cast<DependentNameType>(Y);
14761 assert(NX->getIdentifier() == NY->getIdentifier());
14762 return Ctx.getDependentNameType(
14763 getCommonTypeKeyword(NX, NY, /*IsSame=*/true),
14764 getCommonQualifier(Ctx, NX, NY, /*IsSame=*/true), NX->getIdentifier());
14765 }
14766 case Type::OverflowBehavior: {
14767 const auto *NX = cast<OverflowBehaviorType>(X),
14769 assert(NX->getBehaviorKind() == NY->getBehaviorKind());
14770 return Ctx.getOverflowBehaviorType(
14771 NX->getBehaviorKind(),
14772 getCommonTypeWithQualifierLifting(Ctx, NX->getUnderlyingType(),
14773 NY->getUnderlyingType(), QX, QY));
14774 }
14775 case Type::UnaryTransform: {
14776 const auto *TX = cast<UnaryTransformType>(X),
14777 *TY = cast<UnaryTransformType>(Y);
14778 assert(TX->getUTTKind() == TY->getUTTKind());
14779 return Ctx.getUnaryTransformType(
14780 Ctx.getCommonSugaredType(TX->getBaseType(), TY->getBaseType()),
14781 Ctx.getCommonSugaredType(TX->getUnderlyingType(),
14782 TY->getUnderlyingType()),
14783 TX->getUTTKind());
14784 }
14785 case Type::PackExpansion: {
14786 const auto *PX = cast<PackExpansionType>(X),
14787 *PY = cast<PackExpansionType>(Y);
14788 assert(PX->getNumExpansions() == PY->getNumExpansions());
14789 return Ctx.getPackExpansionType(
14790 Ctx.getCommonSugaredType(PX->getPattern(), PY->getPattern()),
14791 PX->getNumExpansions(), false);
14792 }
14793 case Type::Pipe: {
14794 const auto *PX = cast<PipeType>(X), *PY = cast<PipeType>(Y);
14795 assert(PX->isReadOnly() == PY->isReadOnly());
14796 auto MP = PX->isReadOnly() ? &ASTContext::getReadPipeType
14798 return (Ctx.*MP)(getCommonElementType(Ctx, PX, PY));
14799 }
14800 case Type::TemplateTypeParm: {
14801 const auto *TX = cast<TemplateTypeParmType>(X),
14803 assert(TX->getDepth() == TY->getDepth());
14804 assert(TX->getIndex() == TY->getIndex());
14805 assert(TX->isParameterPack() == TY->isParameterPack());
14806 return Ctx.getTemplateTypeParmType(
14807 TX->getDepth(), TX->getIndex(), TX->isParameterPack(),
14808 getCommonDecl(TX->getDecl(), TY->getDecl()));
14809 }
14810 }
14811 llvm_unreachable("Unknown Type Class");
14812}
14813
14815 const Type *Y,
14816 SplitQualType Underlying) {
14817 Type::TypeClass TC = X->getTypeClass();
14818 if (TC != Y->getTypeClass())
14819 return QualType();
14820 switch (TC) {
14821#define UNEXPECTED_TYPE(Class, Kind) \
14822 case Type::Class: \
14823 llvm_unreachable("Unexpected " Kind ": " #Class);
14824#define TYPE(Class, Base)
14825#define DEPENDENT_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "dependent")
14826#include "clang/AST/TypeNodes.inc"
14827
14828#define CANONICAL_TYPE(Class) UNEXPECTED_TYPE(Class, "canonical")
14831 CANONICAL_TYPE(BlockPointer)
14834 CANONICAL_TYPE(ConstantArray)
14835 CANONICAL_TYPE(ArrayParameter)
14836 CANONICAL_TYPE(ConstantMatrix)
14838 CANONICAL_TYPE(ExtVector)
14839 CANONICAL_TYPE(FunctionNoProto)
14840 CANONICAL_TYPE(FunctionProto)
14841 CANONICAL_TYPE(IncompleteArray)
14842 CANONICAL_TYPE(HLSLAttributedResource)
14843 CANONICAL_TYPE(HLSLInlineSpirv)
14844 CANONICAL_TYPE(LValueReference)
14845 CANONICAL_TYPE(ObjCInterface)
14846 CANONICAL_TYPE(ObjCObject)
14847 CANONICAL_TYPE(ObjCObjectPointer)
14848 CANONICAL_TYPE(OverflowBehavior)
14852 CANONICAL_TYPE(RValueReference)
14853 CANONICAL_TYPE(VariableArray)
14855#undef CANONICAL_TYPE
14856
14857#undef UNEXPECTED_TYPE
14858
14859 case Type::Adjusted: {
14860 const auto *AX = cast<AdjustedType>(X), *AY = cast<AdjustedType>(Y);
14861 QualType OX = AX->getOriginalType(), OY = AY->getOriginalType();
14862 if (!Ctx.hasSameType(OX, OY))
14863 return QualType();
14864 // FIXME: It's inefficient to have to unify the original types.
14865 return Ctx.getAdjustedType(Ctx.getCommonSugaredType(OX, OY),
14866 Ctx.getQualifiedType(Underlying));
14867 }
14868 case Type::Decayed: {
14869 const auto *DX = cast<DecayedType>(X), *DY = cast<DecayedType>(Y);
14870 QualType OX = DX->getOriginalType(), OY = DY->getOriginalType();
14871 if (!Ctx.hasSameType(OX, OY))
14872 return QualType();
14873 // FIXME: It's inefficient to have to unify the original types.
14874 return Ctx.getDecayedType(Ctx.getCommonSugaredType(OX, OY),
14875 Ctx.getQualifiedType(Underlying));
14876 }
14877 case Type::Attributed: {
14878 const auto *AX = cast<AttributedType>(X), *AY = cast<AttributedType>(Y);
14879 AttributedType::Kind Kind = AX->getAttrKind();
14880 if (Kind != AY->getAttrKind())
14881 return QualType();
14882 QualType MX = AX->getModifiedType(), MY = AY->getModifiedType();
14883 if (!Ctx.hasSameType(MX, MY))
14884 return QualType();
14885 // FIXME: It's inefficient to have to unify the modified types.
14886 return Ctx.getAttributedType(Kind, Ctx.getCommonSugaredType(MX, MY),
14887 Ctx.getQualifiedType(Underlying),
14888 AX->getAttr());
14889 }
14890 case Type::BTFTagAttributed: {
14891 const auto *BX = cast<BTFTagAttributedType>(X);
14892 const BTFTypeTagAttr *AX = BX->getAttr();
14893 // The attribute is not uniqued, so just compare the tag.
14894 if (AX->getBTFTypeTag() !=
14895 cast<BTFTagAttributedType>(Y)->getAttr()->getBTFTypeTag())
14896 return QualType();
14897 return Ctx.getBTFTagAttributedType(AX, Ctx.getQualifiedType(Underlying));
14898 }
14899 case Type::Auto: {
14900 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
14901 assert(AX->getDeducedKind() == DeducedKind::Deduced);
14902 assert(AY->getDeducedKind() == DeducedKind::Deduced);
14903
14904 AutoTypeKeyword KW = AX->getKeyword();
14905 if (KW != AY->getKeyword())
14906 return QualType();
14907
14908 TemplateDecl *CD =
14909 ::getCommonDecl(AX->getTypeConstraintConcept().getAsTemplateDecl(),
14910 AY->getTypeConstraintConcept().getAsTemplateDecl());
14912 if (CD &&
14913 getCommonTemplateArguments(Ctx, As, AX->getTypeConstraintArguments(),
14914 AY->getTypeConstraintArguments())) {
14915 CD = nullptr; // The arguments differ, so make it unconstrained.
14916 As.clear();
14917 }
14918
14919 // Both auto types can't be dependent, otherwise they wouldn't have been
14920 // sugar. This implies they can't contain unexpanded packs either.
14922 Ctx.getQualifiedType(Underlying), AX->getKeyword(),
14923 TemplateName(CD), As);
14924 }
14925 case Type::PackIndexing:
14926 case Type::Decltype:
14927 return QualType();
14928 case Type::DeducedTemplateSpecialization:
14929 // FIXME: Try to merge these.
14930 return QualType();
14931 case Type::MacroQualified: {
14932 const auto *MX = cast<MacroQualifiedType>(X),
14933 *MY = cast<MacroQualifiedType>(Y);
14934 const IdentifierInfo *IX = MX->getMacroIdentifier();
14935 if (IX != MY->getMacroIdentifier())
14936 return QualType();
14937 return Ctx.getMacroQualifiedType(Ctx.getQualifiedType(Underlying), IX);
14938 }
14939 case Type::SubstTemplateTypeParm: {
14940 const auto *SX = cast<SubstTemplateTypeParmType>(X),
14942 Decl *CD =
14943 ::getCommonDecl(SX->getAssociatedDecl(), SY->getAssociatedDecl());
14944 if (!CD)
14945 return QualType();
14946 unsigned Index = SX->getIndex();
14947 if (Index != SY->getIndex())
14948 return QualType();
14949 auto PackIndex = SX->getPackIndex();
14950 if (PackIndex != SY->getPackIndex())
14951 return QualType();
14952 return Ctx.getSubstTemplateTypeParmType(Ctx.getQualifiedType(Underlying),
14953 CD, Index, PackIndex,
14954 SX->getFinal() && SY->getFinal());
14955 }
14956 case Type::ObjCTypeParam:
14957 // FIXME: Try to merge these.
14958 return QualType();
14959 case Type::Paren:
14960 return Ctx.getParenType(Ctx.getQualifiedType(Underlying));
14961
14962 case Type::TemplateSpecialization: {
14963 const auto *TX = cast<TemplateSpecializationType>(X),
14965 TemplateName CTN =
14966 ::getCommonTemplateName(Ctx, TX->getTemplateName(),
14967 TY->getTemplateName(), /*IgnoreDeduced=*/true);
14968 if (!CTN.getAsVoidPointer())
14969 return QualType();
14971 if (getCommonTemplateArguments(Ctx, As, TX->template_arguments(),
14972 TY->template_arguments()))
14973 return QualType();
14975 getCommonTypeKeyword(TX, TY, /*IsSame=*/false), CTN, As,
14976 /*CanonicalArgs=*/{}, Ctx.getQualifiedType(Underlying));
14977 }
14978 case Type::Typedef: {
14979 const auto *TX = cast<TypedefType>(X), *TY = cast<TypedefType>(Y);
14980 const TypedefNameDecl *CD = ::getCommonDecl(TX->getDecl(), TY->getDecl());
14981 if (!CD)
14982 return QualType();
14983 return Ctx.getTypedefType(
14984 ::getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14985 ::getCommonQualifier(Ctx, TX, TY, /*IsSame=*/false), CD,
14986 Ctx.getQualifiedType(Underlying));
14987 }
14988 case Type::TypeOf: {
14989 // The common sugar between two typeof expressions, where one is
14990 // potentially a typeof_unqual and the other is not, we unify to the
14991 // qualified type as that retains the most information along with the type.
14992 // We only return a typeof_unqual type when both types are unqual types.
14997 return Ctx.getTypeOfType(Ctx.getQualifiedType(Underlying), Kind);
14998 }
14999 case Type::TypeOfExpr:
15000 return QualType();
15001
15002 case Type::UnaryTransform: {
15003 const auto *UX = cast<UnaryTransformType>(X),
15004 *UY = cast<UnaryTransformType>(Y);
15005 UnaryTransformType::UTTKind KX = UX->getUTTKind();
15006 if (KX != UY->getUTTKind())
15007 return QualType();
15008 QualType BX = UX->getBaseType(), BY = UY->getBaseType();
15009 if (!Ctx.hasSameType(BX, BY))
15010 return QualType();
15011 // FIXME: It's inefficient to have to unify the base types.
15012 return Ctx.getUnaryTransformType(Ctx.getCommonSugaredType(BX, BY),
15013 Ctx.getQualifiedType(Underlying), KX);
15014 }
15015 case Type::Using: {
15016 const auto *UX = cast<UsingType>(X), *UY = cast<UsingType>(Y);
15017 const UsingShadowDecl *CD = ::getCommonDecl(UX->getDecl(), UY->getDecl());
15018 if (!CD)
15019 return QualType();
15020 return Ctx.getUsingType(::getCommonTypeKeyword(UX, UY, /*IsSame=*/false),
15021 ::getCommonQualifier(Ctx, UX, UY, /*IsSame=*/false),
15022 CD, Ctx.getQualifiedType(Underlying));
15023 }
15024 case Type::MemberPointer: {
15025 const auto *PX = cast<MemberPointerType>(X),
15026 *PY = cast<MemberPointerType>(Y);
15027 CXXRecordDecl *Cls = PX->getMostRecentCXXRecordDecl();
15028 assert(Cls == PY->getMostRecentCXXRecordDecl());
15029 return Ctx.getMemberPointerType(
15030 ::getCommonPointeeType(Ctx, PX, PY),
15031 ::getCommonQualifier(Ctx, PX, PY, /*IsSame=*/false), Cls);
15032 }
15033 case Type::CountAttributed: {
15034 const auto *DX = cast<CountAttributedType>(X),
15036 if (DX->isCountInBytes() != DY->isCountInBytes())
15037 return QualType();
15038 if (DX->isOrNull() != DY->isOrNull())
15039 return QualType();
15040 Expr *CEX = DX->getCountExpr();
15041 Expr *CEY = DY->getCountExpr();
15042 ArrayRef<clang::TypeCoupledDeclRefInfo> CDX = DX->getCoupledDecls();
15043 if (Ctx.hasSameExpr(CEX, CEY))
15044 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX,
15045 DX->isCountInBytes(), DX->isOrNull(),
15046 CDX);
15047 if (!CEX->isIntegerConstantExpr(Ctx) || !CEY->isIntegerConstantExpr(Ctx))
15048 return QualType();
15049 // Two declarations with the same integer constant may still differ in their
15050 // expression pointers, so we need to evaluate them.
15051 llvm::APSInt VX = *CEX->getIntegerConstantExpr(Ctx);
15052 llvm::APSInt VY = *CEY->getIntegerConstantExpr(Ctx);
15053 if (VX != VY)
15054 return QualType();
15055 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX,
15056 DX->isCountInBytes(), DX->isOrNull(),
15057 CDX);
15058 }
15059
15060 case Type::LateParsedAttr:
15061 return QualType();
15062
15063 case Type::PredefinedSugar:
15064 assert(cast<PredefinedSugarType>(X)->getKind() !=
15066 return QualType();
15067 }
15068 llvm_unreachable("Unhandled Type Class");
15069}
15070
15071static auto unwrapSugar(SplitQualType &T, Qualifiers &QTotal) {
15073 while (true) {
15074 QTotal.addConsistentQualifiers(T.Quals);
15075 QualType NT = T.Ty->getLocallyUnqualifiedSingleStepDesugaredType();
15076 if (NT == QualType(T.Ty, 0))
15077 break;
15078 R.push_back(T);
15079 T = NT.split();
15080 }
15081 return R;
15082}
15083
15085 bool Unqualified) const {
15086 assert(Unqualified ? hasSameUnqualifiedType(X, Y) : hasSameType(X, Y));
15087 if (X == Y)
15088 return X;
15089 if (!Unqualified) {
15090 if (X.isCanonical())
15091 return X;
15092 if (Y.isCanonical())
15093 return Y;
15094 }
15095
15096 SplitQualType SX = X.split(), SY = Y.split();
15097 Qualifiers QX, QY;
15098 // Desugar SX and SY, setting the sugar and qualifiers aside into Xs and Ys,
15099 // until we reach their underlying "canonical nodes". Note these are not
15100 // necessarily canonical types, as they may still have sugared properties.
15101 // QX and QY will store the sum of all qualifiers in Xs and Ys respectively.
15102 auto Xs = ::unwrapSugar(SX, QX), Ys = ::unwrapSugar(SY, QY);
15103
15104 // If this is an ArrayType, the element qualifiers are interchangeable with
15105 // the top level qualifiers.
15106 // * In case the canonical nodes are the same, the elements types are already
15107 // the same.
15108 // * Otherwise, the element types will be made the same, and any different
15109 // element qualifiers will be moved up to the top level qualifiers, per
15110 // 'getCommonArrayElementType'.
15111 // In both cases, this means there may be top level qualifiers which differ
15112 // between X and Y. If so, these differing qualifiers are redundant with the
15113 // element qualifiers, and can be removed without changing the canonical type.
15114 // The desired behaviour is the same as for the 'Unqualified' case here:
15115 // treat the redundant qualifiers as sugar, remove the ones which are not
15116 // common to both sides.
15117 bool KeepCommonQualifiers =
15119
15120 if (SX.Ty != SY.Ty) {
15121 // The canonical nodes differ. Build a common canonical node out of the two,
15122 // unifying their sugar. This may recurse back here.
15123 SX.Ty =
15124 ::getCommonNonSugarTypeNode(*this, SX.Ty, QX, SY.Ty, QY).getTypePtr();
15125 } else {
15126 // The canonical nodes were identical: We may have desugared too much.
15127 // Add any common sugar back in.
15128 while (!Xs.empty() && !Ys.empty() && Xs.back().Ty == Ys.back().Ty) {
15129 QX -= SX.Quals;
15130 QY -= SY.Quals;
15131 SX = Xs.pop_back_val();
15132 SY = Ys.pop_back_val();
15133 }
15134 }
15135 if (KeepCommonQualifiers)
15137 else
15138 assert(QX == QY);
15139
15140 // Even though the remaining sugar nodes in Xs and Ys differ, some may be
15141 // related. Walk up these nodes, unifying them and adding the result.
15142 while (!Xs.empty() && !Ys.empty()) {
15143 auto Underlying = SplitQualType(
15144 SX.Ty, Qualifiers::removeCommonQualifiers(SX.Quals, SY.Quals));
15145 SX = Xs.pop_back_val();
15146 SY = Ys.pop_back_val();
15147 SX.Ty = ::getCommonSugarTypeNode(*this, SX.Ty, SY.Ty, Underlying)
15149 // Stop at the first pair which is unrelated.
15150 if (!SX.Ty) {
15151 SX.Ty = Underlying.Ty;
15152 break;
15153 }
15154 QX -= Underlying.Quals;
15155 };
15156
15157 // Add back the missing accumulated qualifiers, which were stripped off
15158 // with the sugar nodes we could not unify.
15159 QualType R = getQualifiedType(SX.Ty, QX);
15160 assert(Unqualified ? hasSameUnqualifiedType(R, X) : hasSameType(R, X));
15161 return R;
15162}
15163
15165 assert(Ty->isFixedPointType());
15166
15168 return Ty;
15169
15170 switch (Ty->castAs<BuiltinType>()->getKind()) {
15171 default:
15172 llvm_unreachable("Not a saturated fixed point type!");
15173 case BuiltinType::SatShortAccum:
15174 return ShortAccumTy;
15175 case BuiltinType::SatAccum:
15176 return AccumTy;
15177 case BuiltinType::SatLongAccum:
15178 return LongAccumTy;
15179 case BuiltinType::SatUShortAccum:
15180 return UnsignedShortAccumTy;
15181 case BuiltinType::SatUAccum:
15182 return UnsignedAccumTy;
15183 case BuiltinType::SatULongAccum:
15184 return UnsignedLongAccumTy;
15185 case BuiltinType::SatShortFract:
15186 return ShortFractTy;
15187 case BuiltinType::SatFract:
15188 return FractTy;
15189 case BuiltinType::SatLongFract:
15190 return LongFractTy;
15191 case BuiltinType::SatUShortFract:
15192 return UnsignedShortFractTy;
15193 case BuiltinType::SatUFract:
15194 return UnsignedFractTy;
15195 case BuiltinType::SatULongFract:
15196 return UnsignedLongFractTy;
15197 }
15198}
15199
15201 assert(Ty->isFixedPointType());
15202
15203 if (Ty->isSaturatedFixedPointType()) return Ty;
15204
15205 switch (Ty->castAs<BuiltinType>()->getKind()) {
15206 default:
15207 llvm_unreachable("Not a fixed point type!");
15208 case BuiltinType::ShortAccum:
15209 return SatShortAccumTy;
15210 case BuiltinType::Accum:
15211 return SatAccumTy;
15212 case BuiltinType::LongAccum:
15213 return SatLongAccumTy;
15214 case BuiltinType::UShortAccum:
15216 case BuiltinType::UAccum:
15217 return SatUnsignedAccumTy;
15218 case BuiltinType::ULongAccum:
15220 case BuiltinType::ShortFract:
15221 return SatShortFractTy;
15222 case BuiltinType::Fract:
15223 return SatFractTy;
15224 case BuiltinType::LongFract:
15225 return SatLongFractTy;
15226 case BuiltinType::UShortFract:
15228 case BuiltinType::UFract:
15229 return SatUnsignedFractTy;
15230 case BuiltinType::ULongFract:
15232 }
15233}
15234
15236 if (LangOpts.OpenCL)
15238
15239 if (LangOpts.CUDA)
15241
15242 return getLangASFromTargetAS(AS);
15243}
15244
15246 assert(Ty->isFixedPointType());
15247
15248 const TargetInfo &Target = getTargetInfo();
15249 switch (Ty->castAs<BuiltinType>()->getKind()) {
15250 default:
15251 llvm_unreachable("Not a fixed point type!");
15252 case BuiltinType::ShortAccum:
15253 case BuiltinType::SatShortAccum:
15254 return Target.getShortAccumScale();
15255 case BuiltinType::Accum:
15256 case BuiltinType::SatAccum:
15257 return Target.getAccumScale();
15258 case BuiltinType::LongAccum:
15259 case BuiltinType::SatLongAccum:
15260 return Target.getLongAccumScale();
15261 case BuiltinType::UShortAccum:
15262 case BuiltinType::SatUShortAccum:
15263 return Target.getUnsignedShortAccumScale();
15264 case BuiltinType::UAccum:
15265 case BuiltinType::SatUAccum:
15266 return Target.getUnsignedAccumScale();
15267 case BuiltinType::ULongAccum:
15268 case BuiltinType::SatULongAccum:
15269 return Target.getUnsignedLongAccumScale();
15270 case BuiltinType::ShortFract:
15271 case BuiltinType::SatShortFract:
15272 return Target.getShortFractScale();
15273 case BuiltinType::Fract:
15274 case BuiltinType::SatFract:
15275 return Target.getFractScale();
15276 case BuiltinType::LongFract:
15277 case BuiltinType::SatLongFract:
15278 return Target.getLongFractScale();
15279 case BuiltinType::UShortFract:
15280 case BuiltinType::SatUShortFract:
15281 return Target.getUnsignedShortFractScale();
15282 case BuiltinType::UFract:
15283 case BuiltinType::SatUFract:
15284 return Target.getUnsignedFractScale();
15285 case BuiltinType::ULongFract:
15286 case BuiltinType::SatULongFract:
15287 return Target.getUnsignedLongFractScale();
15288 }
15289}
15290
15292 assert(Ty->isFixedPointType());
15293
15294 const TargetInfo &Target = getTargetInfo();
15295 switch (Ty->castAs<BuiltinType>()->getKind()) {
15296 default:
15297 llvm_unreachable("Not a fixed point type!");
15298 case BuiltinType::ShortAccum:
15299 case BuiltinType::SatShortAccum:
15300 return Target.getShortAccumIBits();
15301 case BuiltinType::Accum:
15302 case BuiltinType::SatAccum:
15303 return Target.getAccumIBits();
15304 case BuiltinType::LongAccum:
15305 case BuiltinType::SatLongAccum:
15306 return Target.getLongAccumIBits();
15307 case BuiltinType::UShortAccum:
15308 case BuiltinType::SatUShortAccum:
15309 return Target.getUnsignedShortAccumIBits();
15310 case BuiltinType::UAccum:
15311 case BuiltinType::SatUAccum:
15312 return Target.getUnsignedAccumIBits();
15313 case BuiltinType::ULongAccum:
15314 case BuiltinType::SatULongAccum:
15315 return Target.getUnsignedLongAccumIBits();
15316 case BuiltinType::ShortFract:
15317 case BuiltinType::SatShortFract:
15318 case BuiltinType::Fract:
15319 case BuiltinType::SatFract:
15320 case BuiltinType::LongFract:
15321 case BuiltinType::SatLongFract:
15322 case BuiltinType::UShortFract:
15323 case BuiltinType::SatUShortFract:
15324 case BuiltinType::UFract:
15325 case BuiltinType::SatUFract:
15326 case BuiltinType::ULongFract:
15327 case BuiltinType::SatULongFract:
15328 return 0;
15329 }
15330}
15331
15332llvm::FixedPointSemantics
15334 assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
15335 "Can only get the fixed point semantics for a "
15336 "fixed point or integer type.");
15337 if (Ty->isIntegerType())
15338 return llvm::FixedPointSemantics::GetIntegerSemantics(
15339 getIntWidth(Ty), Ty->isSignedIntegerType());
15340
15341 bool isSigned = Ty->isSignedFixedPointType();
15342 return llvm::FixedPointSemantics(
15343 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
15345 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
15346}
15347
15348llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
15349 assert(Ty->isFixedPointType());
15350 return llvm::APFixedPoint::getMax(getFixedPointSemantics(Ty));
15351}
15352
15353llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
15354 assert(Ty->isFixedPointType());
15355 return llvm::APFixedPoint::getMin(getFixedPointSemantics(Ty));
15356}
15357
15359 assert(Ty->isUnsignedFixedPointType() &&
15360 "Expected unsigned fixed point type");
15361
15362 switch (Ty->castAs<BuiltinType>()->getKind()) {
15363 case BuiltinType::UShortAccum:
15364 return ShortAccumTy;
15365 case BuiltinType::UAccum:
15366 return AccumTy;
15367 case BuiltinType::ULongAccum:
15368 return LongAccumTy;
15369 case BuiltinType::SatUShortAccum:
15370 return SatShortAccumTy;
15371 case BuiltinType::SatUAccum:
15372 return SatAccumTy;
15373 case BuiltinType::SatULongAccum:
15374 return SatLongAccumTy;
15375 case BuiltinType::UShortFract:
15376 return ShortFractTy;
15377 case BuiltinType::UFract:
15378 return FractTy;
15379 case BuiltinType::ULongFract:
15380 return LongFractTy;
15381 case BuiltinType::SatUShortFract:
15382 return SatShortFractTy;
15383 case BuiltinType::SatUFract:
15384 return SatFractTy;
15385 case BuiltinType::SatULongFract:
15386 return SatLongFractTy;
15387 default:
15388 llvm_unreachable("Unexpected unsigned fixed point type");
15389 }
15390}
15391
15392// Given a list of FMV features, return a concatenated list of the
15393// corresponding backend features (which may contain duplicates).
15394static std::vector<std::string> getFMVBackendFeaturesFor(
15395 const llvm::SmallVectorImpl<StringRef> &FMVFeatStrings) {
15396 std::vector<std::string> BackendFeats;
15397 llvm::AArch64::ExtensionSet FeatureBits;
15398 for (StringRef F : FMVFeatStrings)
15399 if (auto FMVExt = llvm::AArch64::parseFMVExtension(F))
15400 if (FMVExt->ID)
15401 FeatureBits.enable(*FMVExt->ID);
15402 FeatureBits.toLLVMFeatureList(BackendFeats);
15403 return BackendFeats;
15404}
15405
15406ParsedTargetAttr
15407ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const {
15408 assert(TD != nullptr);
15409 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(TD->getFeaturesStr());
15410
15411 llvm::erase_if(ParsedAttr.Features, [&](const std::string &Feat) {
15412 return !Target->isValidFeatureName(StringRef{Feat}.substr(1));
15413 });
15414 return ParsedAttr;
15415}
15416
15417const llvm::StringMap<bool> &
15419 return getFunctionFeatureMap(GlobalDecl().getWithDecl(FD));
15420}
15421
15422const llvm::StringMap<bool> &
15424 const auto *FD = GD.getDecl() ? GD.getDecl()->getAsFunction() : nullptr;
15425 if (!FD || !FD->hasAttrs())
15426 return Target->getTargetOpts().FeatureMap;
15427
15428 const Attr *FeatureAttr;
15429 StringRef FeatureText;
15430 if (const auto *TargetAttribute = FD->getAttr<TargetAttr>()) {
15431 FeatureAttr = TargetAttribute;
15432 FeatureText = TargetAttribute->getFeaturesStr();
15433 } else if (const auto *Specific = FD->getAttr<CPUSpecificAttr>()) {
15434 FeatureAttr = Specific;
15435 FeatureText = Specific->getCPUName(GD.getMultiVersionIndex())->getName();
15436 } else if (const auto *Clones = FD->getAttr<TargetClonesAttr>()) {
15437 FeatureAttr = Clones;
15438 FeatureText = Clones->getFeatureStr(GD.getMultiVersionIndex());
15439 } else if (const auto *Version = FD->getAttr<TargetVersionAttr>()) {
15440 FeatureAttr = Version;
15441 FeatureText = Version->getName();
15442 } else {
15443 return Target->getTargetOpts().FeatureMap;
15444 }
15445
15446 auto Key = std::make_pair(FeatureText, unsigned(FeatureAttr->getKind()));
15447 auto It = FunctionFeatureMaps.find(Key);
15448 if (It != FunctionFeatureMaps.end())
15449 return *It->second;
15450
15451 auto FeatureMap = std::make_unique<llvm::StringMap<bool>>();
15452 getFunctionFeatureMap(*FeatureMap, GD);
15453 return *FunctionFeatureMaps.try_emplace(Key, std::move(FeatureMap))
15454 .first->second;
15455}
15456
15457void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
15458 const FunctionDecl *FD) const {
15459 if (FD)
15460 getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD));
15461 else
15462 Target->initFeatureMap(FeatureMap, getDiagnostics(),
15463 Target->getTargetOpts().CPU,
15464 Target->getTargetOpts().Features);
15465}
15466
15467// Fills in the supplied string map with the set of target features for the
15468// passed in function.
15469void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
15470 GlobalDecl GD) const {
15471 StringRef TargetCPU = Target->getTargetOpts().CPU;
15472 const FunctionDecl *FD = GD.getDecl()->getAsFunction();
15473 if (const auto *TD = FD->getAttr<TargetAttr>()) {
15475
15476 // Make a copy of the features as passed on the command line into the
15477 // beginning of the additional features from the function to override.
15478 // AArch64 handles command line option features in parseTargetAttr().
15479 if (!Target->getTriple().isAArch64())
15480 ParsedAttr.Features.insert(
15481 ParsedAttr.Features.begin(),
15482 Target->getTargetOpts().FeaturesAsWritten.begin(),
15483 Target->getTargetOpts().FeaturesAsWritten.end());
15484
15485 if (ParsedAttr.CPU != "" && Target->isValidCPUName(ParsedAttr.CPU))
15486 TargetCPU = ParsedAttr.CPU;
15487
15488 // Now populate the feature map, first with the TargetCPU which is either
15489 // the default or a new one from the target attribute string. Then we'll use
15490 // the passed in features (FeaturesAsWritten) along with the new ones from
15491 // the attribute.
15492 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU,
15493 ParsedAttr.Features);
15494 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
15496 Target->getCPUSpecificCPUDispatchFeatures(
15497 SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp);
15498 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
15499 Features.insert(Features.begin(),
15500 Target->getTargetOpts().FeaturesAsWritten.begin(),
15501 Target->getTargetOpts().FeaturesAsWritten.end());
15502 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15503 } else if (const auto *TC = FD->getAttr<TargetClonesAttr>()) {
15504 if (Target->getTriple().isAArch64()) {
15506 TC->getFeatures(Feats, GD.getMultiVersionIndex());
15507 std::vector<std::string> Features = getFMVBackendFeaturesFor(Feats);
15508 Features.insert(Features.begin(),
15509 Target->getTargetOpts().FeaturesAsWritten.begin(),
15510 Target->getTargetOpts().FeaturesAsWritten.end());
15511 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15512 } else if (Target->getTriple().isRISCV()) {
15513 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
15514 std::vector<std::string> Features;
15515 if (VersionStr != "default") {
15516 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(VersionStr);
15517 Features.insert(Features.begin(), ParsedAttr.Features.begin(),
15518 ParsedAttr.Features.end());
15519 }
15520 Features.insert(Features.begin(),
15521 Target->getTargetOpts().FeaturesAsWritten.begin(),
15522 Target->getTargetOpts().FeaturesAsWritten.end());
15523 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15524 } else if (Target->getTriple().isOSAIX()) {
15525 std::vector<std::string> Features;
15526 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
15527 if (VersionStr.starts_with("cpu="))
15528 TargetCPU = VersionStr.drop_front(sizeof("cpu=") - 1);
15529 else if (VersionStr != "default")
15530 Features = Target->parseTargetAttr(VersionStr).Features;
15531 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15532 } else {
15533 std::vector<std::string> Features;
15534 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
15535 if (VersionStr.starts_with("arch="))
15536 TargetCPU = VersionStr.drop_front(sizeof("arch=") - 1);
15537 else if (VersionStr != "default")
15538 Features.push_back((StringRef{"+"} + VersionStr).str());
15539 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15540 }
15541 } else if (const auto *TV = FD->getAttr<TargetVersionAttr>()) {
15542 std::vector<std::string> Features;
15543 if (Target->getTriple().isRISCV()) {
15544 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(TV->getName());
15545 Features.insert(Features.begin(), ParsedAttr.Features.begin(),
15546 ParsedAttr.Features.end());
15547 } else {
15548 assert(Target->getTriple().isAArch64());
15550 TV->getFeatures(Feats);
15551 Features = getFMVBackendFeaturesFor(Feats);
15552 }
15553 Features.insert(Features.begin(),
15554 Target->getTargetOpts().FeaturesAsWritten.begin(),
15555 Target->getTargetOpts().FeaturesAsWritten.end());
15556 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15557 } else {
15558 FeatureMap = Target->getTargetOpts().FeatureMap;
15559 }
15560}
15561
15563 CanQualType KernelNameType,
15564 const FunctionDecl *FD) {
15565 // Host and device compilation may use different ABIs and different ABIs
15566 // may allocate name mangling discriminators differently. A discriminator
15567 // override is used to ensure consistent discriminator allocation across
15568 // host and device compilation.
15569 auto DeviceDiscriminatorOverrider =
15570 [](ASTContext &Ctx, const NamedDecl *ND) -> UnsignedOrNone {
15571 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
15572 if (RD->isLambda())
15573 return RD->getDeviceLambdaManglingNumber();
15574 return std::nullopt;
15575 };
15576 std::unique_ptr<MangleContext> MC{ItaniumMangleContext::create(
15577 Context, Context.getDiagnostics(), DeviceDiscriminatorOverrider)};
15578
15579 // Construct a mangled name for the SYCL kernel caller offload entry point.
15580 // FIXME: The Itanium typeinfo mangling (_ZTS<type>) is currently used to
15581 // name the SYCL kernel caller offload entry point function. This mangling
15582 // does not suffice to clearly identify symbols that correspond to SYCL
15583 // kernel caller functions, nor is this mangling natural for targets that
15584 // use a non-Itanium ABI.
15585 std::string Buffer;
15586 Buffer.reserve(128);
15587 llvm::raw_string_ostream Out(Buffer);
15588 MC->mangleCanonicalTypeName(KernelNameType, Out);
15589 std::string KernelName = Out.str();
15590
15591 return {KernelNameType, FD, KernelName};
15592}
15593
15595 // If the function declaration to register is invalid or dependent, the
15596 // registration attempt is ignored.
15597 if (FD->isInvalidDecl() || FD->isTemplated())
15598 return;
15599
15600 const auto *SKEPAttr = FD->getAttr<SYCLKernelEntryPointAttr>();
15601 assert(SKEPAttr && "Missing sycl_kernel_entry_point attribute");
15602
15603 // Be tolerant of multiple registration attempts so long as each attempt
15604 // is for the same entity. Callers are obligated to detect and diagnose
15605 // conflicting kernel names prior to calling this function.
15606 CanQualType KernelNameType = getCanonicalType(SKEPAttr->getKernelName());
15607 auto IT = SYCLKernels.find(KernelNameType);
15608 assert((IT == SYCLKernels.end() ||
15609 declaresSameEntity(FD, IT->second.getKernelEntryPointDecl())) &&
15610 "SYCL kernel name conflict");
15611 (void)IT;
15612 SYCLKernels.insert(std::make_pair(
15613 KernelNameType, BuildSYCLKernelInfo(*this, KernelNameType, FD)));
15614}
15615
15617 CanQualType KernelNameType = getCanonicalType(T);
15618 return SYCLKernels.at(KernelNameType);
15619}
15620
15622 CanQualType KernelNameType = getCanonicalType(T);
15623 auto IT = SYCLKernels.find(KernelNameType);
15624 if (IT != SYCLKernels.end())
15625 return &IT->second;
15626 return nullptr;
15627}
15628
15630 OMPTraitInfoVector.emplace_back(new OMPTraitInfo());
15631 return *OMPTraitInfoVector.back();
15632}
15633
15636 const ASTContext::SectionInfo &Section) {
15637 if (Section.Decl)
15638 return DB << Section.Decl;
15639 return DB << "a prior #pragma section";
15640}
15641
15642bool ASTContext::mayExternalize(const Decl *D) const {
15643 bool IsInternalVar =
15644 isa<VarDecl>(D) &&
15646 bool IsExplicitDeviceVar = (D->hasAttr<CUDADeviceAttr>() &&
15647 !D->getAttr<CUDADeviceAttr>()->isImplicit()) ||
15648 (D->hasAttr<CUDAConstantAttr>() &&
15649 !D->getAttr<CUDAConstantAttr>()->isImplicit());
15650 // CUDA/HIP: managed variables need to be externalized since it is
15651 // a declaration in IR, therefore cannot have internal linkage. Kernels in
15652 // anonymous name space needs to be externalized to avoid duplicate symbols.
15653 return (IsInternalVar &&
15654 (D->hasAttr<HIPManagedAttr>() || IsExplicitDeviceVar)) ||
15655 (D->hasAttr<CUDAGlobalAttr>() &&
15657 GVA_Internal);
15658}
15659
15661 return mayExternalize(D) &&
15662 (D->hasAttr<HIPManagedAttr>() || D->hasAttr<CUDAGlobalAttr>() ||
15664}
15665
15666StringRef ASTContext::getCUIDHash() const {
15667 if (!CUIDHash.empty())
15668 return CUIDHash;
15669 if (LangOpts.CUID.empty())
15670 return StringRef();
15671 CUIDHash = llvm::utohexstr(llvm::MD5Hash(LangOpts.CUID), /*LowerCase=*/true);
15672 return CUIDHash;
15673}
15674
15675const CXXRecordDecl *
15677 assert(ThisClass);
15678 assert(ThisClass->isPolymorphic());
15679 const CXXRecordDecl *PrimaryBase = ThisClass;
15680 while (1) {
15681 assert(PrimaryBase);
15682 assert(PrimaryBase->isPolymorphic());
15683 auto &Layout = getASTRecordLayout(PrimaryBase);
15684 auto Base = Layout.getPrimaryBase();
15685 if (!Base || Base == PrimaryBase || !Base->isPolymorphic())
15686 break;
15687 PrimaryBase = Base;
15688 }
15689 return PrimaryBase;
15690}
15691
15693 StringRef MangledName) {
15694 auto *Method = cast<CXXMethodDecl>(VirtualMethodDecl.getDecl());
15695 assert(Method->isVirtual());
15696 bool DefaultIncludesPointerAuth =
15697 LangOpts.PointerAuthCalls || LangOpts.PointerAuthIntrinsics;
15698
15699 if (!DefaultIncludesPointerAuth)
15700 return true;
15701
15702 auto Existing = ThunksToBeAbbreviated.find(VirtualMethodDecl);
15703 if (Existing != ThunksToBeAbbreviated.end())
15704 return Existing->second.contains(MangledName.str());
15705
15706 std::unique_ptr<MangleContext> Mangler(createMangleContext());
15707 llvm::StringMap<llvm::SmallVector<std::string, 2>> Thunks;
15708 auto VtableContext = getVTableContext();
15709 if (const auto *ThunkInfos = VtableContext->getThunkInfo(VirtualMethodDecl)) {
15710 auto *Destructor = dyn_cast<CXXDestructorDecl>(Method);
15711 for (const auto &Thunk : *ThunkInfos) {
15712 SmallString<256> ElidedName;
15713 llvm::raw_svector_ostream ElidedNameStream(ElidedName);
15714 if (Destructor)
15715 Mangler->mangleCXXDtorThunk(Destructor, VirtualMethodDecl.getDtorType(),
15716 Thunk, /* elideOverrideInfo */ true,
15717 ElidedNameStream);
15718 else
15719 Mangler->mangleThunk(Method, Thunk, /* elideOverrideInfo */ true,
15720 ElidedNameStream);
15721 SmallString<256> MangledName;
15722 llvm::raw_svector_ostream mangledNameStream(MangledName);
15723 if (Destructor)
15724 Mangler->mangleCXXDtorThunk(Destructor, VirtualMethodDecl.getDtorType(),
15725 Thunk, /* elideOverrideInfo */ false,
15726 mangledNameStream);
15727 else
15728 Mangler->mangleThunk(Method, Thunk, /* elideOverrideInfo */ false,
15729 mangledNameStream);
15730
15731 Thunks[ElidedName].push_back(std::string(MangledName));
15732 }
15733 }
15734 llvm::StringSet<> SimplifiedThunkNames;
15735 for (auto &ThunkList : Thunks) {
15736 llvm::sort(ThunkList.second);
15737 SimplifiedThunkNames.insert(ThunkList.second[0]);
15738 }
15739 bool Result = SimplifiedThunkNames.contains(MangledName);
15740 ThunksToBeAbbreviated[VirtualMethodDecl] = std::move(SimplifiedThunkNames);
15741 return Result;
15742}
15743
15745 // Check for trivially-destructible here because non-trivially-destructible
15746 // types will always cause the type and any types derived from it to be
15747 // considered non-trivially-copyable. The same cannot be said for
15748 // trivially-copyable because deleting special members of a type derived from
15749 // a non-trivially-copyable type can cause the derived type to be considered
15750 // trivially copyable.
15751 if (getLangOpts().PointerFieldProtectionTagged)
15752 return !isa<CXXRecordDecl>(RD) ||
15753 cast<CXXRecordDecl>(RD)->hasTrivialDestructor();
15754 return true;
15755}
15756
15757static void findPFPFields(const ASTContext &Ctx, QualType Ty, CharUnits Offset,
15758 std::vector<PFPField> &Fields, bool IncludeVBases) {
15759 if (auto *AT = Ctx.getAsConstantArrayType(Ty)) {
15760 if (auto *ElemDecl = AT->getElementType()->getAsCXXRecordDecl()) {
15761 const ASTRecordLayout &ElemRL = Ctx.getASTRecordLayout(ElemDecl);
15762 for (unsigned i = 0; i != AT->getSize(); ++i)
15763 findPFPFields(Ctx, AT->getElementType(), Offset + i * ElemRL.getSize(),
15764 Fields, true);
15765 }
15766 }
15767 auto *Decl = Ty->getAsCXXRecordDecl();
15768 // isPFPType() is inherited from bases and members (including via arrays), so
15769 // we can early exit if it is false. Unions are excluded per the API
15770 // documentation.
15771 if (!Decl || !Decl->isPFPType() || Decl->isUnion())
15772 return;
15773 const ASTRecordLayout &RL = Ctx.getASTRecordLayout(Decl);
15774 for (FieldDecl *Field : Decl->fields()) {
15775 CharUnits FieldOffset =
15776 Offset +
15777 Ctx.toCharUnitsFromBits(RL.getFieldOffset(Field->getFieldIndex()));
15778 if (Ctx.isPFPField(Field))
15779 Fields.push_back({FieldOffset, Field});
15780 findPFPFields(Ctx, Field->getType(), FieldOffset, Fields,
15781 /*IncludeVBases=*/true);
15782 }
15783 // Pass false for IncludeVBases below because vbases are only included in
15784 // layout for top-level types, i.e. not bases or vbases.
15785 for (CXXBaseSpecifier &Base : Decl->bases()) {
15786 if (Base.isVirtual())
15787 continue;
15788 CharUnits BaseOffset =
15789 Offset + RL.getBaseClassOffset(Base.getType()->getAsCXXRecordDecl());
15790 findPFPFields(Ctx, Base.getType(), BaseOffset, Fields,
15791 /*IncludeVBases=*/false);
15792 }
15793 if (IncludeVBases) {
15794 for (CXXBaseSpecifier &Base : Decl->vbases()) {
15795 CharUnits BaseOffset =
15796 Offset + RL.getVBaseClassOffset(Base.getType()->getAsCXXRecordDecl());
15797 findPFPFields(Ctx, Base.getType(), BaseOffset, Fields,
15798 /*IncludeVBases=*/false);
15799 }
15800 }
15801}
15802
15803std::vector<PFPField> ASTContext::findPFPFields(QualType Ty) const {
15804 std::vector<PFPField> PFPFields;
15805 ::findPFPFields(*this, Ty, CharUnits::Zero(), PFPFields, true);
15806 return PFPFields;
15807}
15808
15810 return !findPFPFields(Ty).empty();
15811}
15812
15814 if (auto *RD = dyn_cast<CXXRecordDecl>(FD->getParent()))
15815 return RD->isPFPType() && FD->getType()->isPointerType() &&
15816 !FD->hasAttr<NoFieldProtectionAttr>();
15817 return false;
15818}
15819
15821 auto *FD = dyn_cast<FieldDecl>(VD);
15822 if (!FD)
15823 FD = cast<FieldDecl>(cast<IndirectFieldDecl>(VD)->chain().back());
15824 if (isPFPField(FD))
15826}
15827
15829 if (E->getNumComponents() == 0)
15830 return;
15831 OffsetOfNode Comp = E->getComponent(E->getNumComponents() - 1);
15832 if (Comp.getKind() != OffsetOfNode::Field)
15833 return;
15834 if (FieldDecl *FD = Comp.getField(); isPFPField(FD))
15836}
15837
15838namespace {
15839// PaddingCalculator is a utility class that calculates the padding bits in a
15840// c/c++ type. It traverses the type recursively, collecting occupied
15841// bit intervals, and then computes the padding intervals.
15842// If a byte only contains some padding bits, it gets intervals for only those
15843// bits. This is the case for bit-fields.
15844struct PaddingCalculator {
15845 PaddingCalculator(const ASTContext &Ctx) : Ctx(Ctx) {}
15846
15847 void run(QualType Ty) {
15848 OccuppiedIntervals.clear();
15849 Stack.clear();
15850
15851 TySizeInBits = Ctx.getTypeSize(Ty);
15852
15853 Stack.push_back(Data{0, Ty.getCanonicalType(), true});
15854 while (!Stack.empty()) {
15855 Data Current = Stack.back();
15856 Stack.pop_back();
15857 Visit(Current);
15858 }
15859 MergeOccuppiedIntervals();
15860 }
15861
15862 llvm::SmallVector<ASTContext::BitInterval> GetPaddingIntervals() {
15863 llvm::SmallVector<ASTContext::BitInterval> Results;
15864 if (OccuppiedIntervals.size() == 1 &&
15865 OccuppiedIntervals.front().First == 0 &&
15866 OccuppiedIntervals.front().Last == TySizeInBits) {
15867 return Results;
15868 }
15869 Results.reserve(OccuppiedIntervals.size() + 1);
15870 uint64_t CurrentPos = 0;
15871 for (const ASTContext::BitInterval &OccupiedInterval : OccuppiedIntervals) {
15872 if (OccupiedInterval.First > CurrentPos) {
15873 Results.push_back(
15874 ASTContext::BitInterval{CurrentPos, OccupiedInterval.First});
15875 }
15876 CurrentPos = OccupiedInterval.Last;
15877 }
15878 if (TySizeInBits > CurrentPos) {
15879 Results.push_back(ASTContext::BitInterval{CurrentPos, TySizeInBits});
15880 }
15881 return Results;
15882 }
15883
15884private:
15885 struct Data {
15886 uint64_t StartBitOffset;
15887 QualType Ty;
15888 bool VisitVirtualBase;
15889 };
15890
15891 // Return the number of non padding bits of a scalar type.
15892 //
15893 // The property that we specifically care about here is whether the scalar
15894 // type has padding bits, i.e. are there bits in the type which are not
15895 // specified by the ABI.
15896 //
15897 // We currently don't care about this anywhere else in clang: layout cares
15898 // about the ABI size, calling convention code cares about specific types,
15899 // but nothing cares about padding specifically. And it's not something we can
15900 // easily query from LLVM due to the type system mismatches.
15901 // DL.getTypeSizeInBits(convertTypeForLoadStore(T)) is probably close, but the
15902 // DataLayout methods aren't really designed for this usage.
15903 //
15904 // Therefore, it is better to explicitly list all the scalar types
15905 // containing padding bits that we know of, namely, _BitInt(N) and x87 long
15906 // double.
15907 //
15908 // FIXME: There are likely other scalar types we need to think about here, as
15909 // brought up in review for #215823:
15910 // - bool
15911 // - enums(both with/without fixed underlying type)
15912 // - nullptr_t
15913 // - more?
15914 uint64_t getScalarOccupiedSizeInBits(QualType Ty) const {
15915 if (const auto *BIT = Ty->getAs<BitIntType>())
15916 return BIT->getNumBits();
15917
15918 if (const auto *BT = Ty->getAs<BuiltinType>()) {
15919 if (BT->getKind() == BuiltinType::LongDouble &&
15921 &llvm::APFloat::x87DoubleExtended())
15922 return llvm::APFloat::getSizeInBits(
15924 }
15925
15926 return Ctx.getTypeSize(Ty);
15927 }
15928
15929 void Visit(const Data &D) {
15930 if (auto *AT = dyn_cast<ConstantArrayType>(D.Ty)) {
15931 VisitArray(AT, D.StartBitOffset);
15932 return;
15933 }
15934
15935 if (auto *Record = D.Ty->getAsRecordDecl()) {
15936 VisitStruct(Record, D.StartBitOffset, D.VisitVirtualBase);
15937 return;
15938 }
15939
15940 if (D.Ty->isAtomicType()) {
15941 auto Unwrapped = D;
15942 Unwrapped.Ty = D.Ty.getAtomicUnqualifiedType().getCanonicalType();
15943 Stack.push_back(Unwrapped);
15944 return;
15945 }
15946
15947 if (const auto *Complex = D.Ty->getAs<ComplexType>()) {
15948 VisitComplex(Complex, D.StartBitOffset);
15949 return;
15950 }
15951
15952 if (const auto *VT = D.Ty->getAs<clang::VectorType>()) {
15953 VisitVector(VT, D.StartBitOffset);
15954 return;
15955 }
15956
15957 if (const auto *BITy = D.Ty->getAs<BitIntType>()) {
15958 VisitBitInt(BITy, D.StartBitOffset);
15959 return;
15960 }
15961
15962 uint64_t SizeBit = getScalarOccupiedSizeInBits(D.Ty);
15963 OccuppiedIntervals.push_back(
15964 ASTContext::BitInterval{D.StartBitOffset, D.StartBitOffset + SizeBit});
15965 }
15966
15967 void VisitArray(const ConstantArrayType *AT, uint64_t StartBitOffset) {
15968 for (uint64_t ArrIndex = 0; ArrIndex < AT->getSize().getLimitedValue();
15969 ++ArrIndex) {
15970
15971 QualType ElementQualType = AT->getElementType();
15972 auto ElementSize = Ctx.getTypeSizeInChars(ElementQualType);
15973 auto ElementAlign = Ctx.getTypeAlignInChars(ElementQualType);
15974 auto Offset = ElementSize.alignTo(ElementAlign);
15975
15976 Stack.push_back(Data{
15977 StartBitOffset + ArrIndex * Offset.getQuantity() * Ctx.getCharWidth(),
15978 ElementQualType.getCanonicalType(), /*VisitVirtualBase*/ true});
15979 }
15980 }
15981
15982 void VisitStruct(const RecordDecl *R, uint64_t StartBitOffset,
15983 bool VisitVirtualBase) {
15984 const ASTRecordLayout &ASTLayout = Ctx.getASTRecordLayout(R);
15985 auto *CXXRecord = dyn_cast<CXXRecordDecl>(R);
15986
15987 unsigned PointerSizeInBits = Ctx.getTypeSize(Ctx.NullPtrTy);
15988
15989 if (CXXRecord) {
15990 if (ASTLayout.hasOwnVFPtr()) {
15991 OccuppiedIntervals.push_back(ASTContext::BitInterval{
15992 StartBitOffset, StartBitOffset + PointerSizeInBits});
15993 }
15994
15995 if (ASTLayout.hasOwnVBPtr()) {
15996 auto Offset = ASTLayout.getVBPtrOffset().getQuantity();
15997 auto StartVBPtr = StartBitOffset + Offset * Ctx.getCharWidth();
15998 OccuppiedIntervals.push_back(ASTContext::BitInterval{
15999 StartVBPtr, StartVBPtr + PointerSizeInBits});
16000 }
16001
16002 const auto VisitBase = [&ASTLayout, StartBitOffset, this](
16003 const CXXBaseSpecifier &Base, auto GetOffset) {
16004 auto *BaseRecord = Base.getType()->getAsCXXRecordDecl();
16005 if (!BaseRecord) {
16006 return;
16007 }
16008 auto BaseOffset =
16009 std::invoke(GetOffset, ASTLayout, BaseRecord).getQuantity();
16010
16011 Stack.push_back(
16012 Data{StartBitOffset + BaseOffset * Ctx.getCharWidth(),
16013 Base.getType().getCanonicalType(), /*VisitVirtualBase*/
16014 false});
16015 };
16016
16017 for (auto Base : CXXRecord->bases()) {
16018 if (!Base.isVirtual()) {
16019 VisitBase(Base, &ASTRecordLayout::getBaseClassOffset);
16020 }
16021 }
16022
16023 if (VisitVirtualBase) {
16024 for (auto VBase : CXXRecord->vbases()) {
16025 VisitBase(VBase, &ASTRecordLayout::getVBaseClassOffset);
16026 }
16027 }
16028 }
16029
16030 for (auto *Field : R->fields()) {
16031 // Treat unnamed bitfields as padding.
16032 if (Field->isUnnamedBitField())
16033 continue;
16034
16035 auto FieldOffset = ASTLayout.getFieldOffset(Field->getFieldIndex());
16036 if (Field->isBitField()) {
16037 VisitBitfield(Field, StartBitOffset + FieldOffset);
16038 } else {
16039 Stack.push_back(Data{StartBitOffset + FieldOffset,
16040 Field->getType().getCanonicalType(),
16041 /*VisitVirtualBase*/ true});
16042 }
16043 }
16044 }
16045
16046 void VisitBitfield(const FieldDecl *Field, uint64_t StartBitOffset) {
16047 assert(Field->isBitField() && !Field->isUnnamedBitField());
16048 if (Field->isZeroLengthBitField())
16049 return;
16050
16051 const uint64_t DeclaredSizeInBits = Field->getBitWidthValue();
16052
16053 // Oversized bit-fields (declared width larger than the field type) occupy
16054 // only the type's width. The extra declared bits are padding and follow
16055 // the occupied bits (Itanium C++ ABI §2.4, II.1(b)).
16056 // In case where the bitfield can only have values with a range smaller than
16057 // the one declared, e.g. bool a : 5 or _BitInt(5) b : 6, the remaining bits
16058 // within the bitfield are for sign or zero extension. These are considered
16059 // occupied as well.
16060 const uint64_t OccupiedSizeInBits =
16061 std::min(DeclaredSizeInBits, Ctx.getTypeSize(Field->getType()));
16062
16063 if (Ctx.getTargetInfo().isLittleEndian()) {
16064 OccuppiedIntervals.push_back(
16065 {StartBitOffset, StartBitOffset + OccupiedSizeInBits});
16066 return;
16067 }
16068
16069 // In big endian mode, the sequence of occupied bits traverses bytes in
16070 // increasing address order, just like in little endian. However, within
16071 // each byte, the traversal starts from the most significant bit. This is
16072 // where it differs from little endian.
16073 //
16074 // If the interval contains whole bytes in the middle, then for these
16075 // nothing changes, and they constitute a contiguous interval. However for
16076 // the partially occupied bytes in either end, if present, their bit
16077 // intervals need to be adjusted so that they count from the MSB instead.
16078 //
16079 // Occupied bits are allocated first, and any padding follows them.
16080 const uint64_t Start = StartBitOffset;
16081 const uint64_t End = Start + OccupiedSizeInBits;
16082 const uint64_t CharWidth = Ctx.getCharWidth();
16083
16084 // Special case: all the occupied bits are contained within a single byte.
16085 const uint64_t ByteStart = llvm::alignDown(Start, CharWidth);
16086 const uint64_t ByteEnd = llvm::alignTo(End, CharWidth);
16087 if (ByteStart == ByteEnd - CharWidth) {
16088 const uint64_t Length = End - Start;
16089 const uint64_t Offset = Start - ByteStart;
16090 OccuppiedIntervals.push_back(
16091 {ByteEnd - Offset - Length, ByteEnd - Offset});
16092 return;
16093 }
16094
16095 // Compute the contiguous interval in the middle, comprised of whole bytes,
16096 // if any.
16097 const uint64_t MiddleIntervalStart = llvm::alignTo(Start, CharWidth);
16098 const uint64_t MiddleIntervalEnd = llvm::alignDown(End, CharWidth);
16099 if (MiddleIntervalStart != MiddleIntervalEnd)
16100 OccuppiedIntervals.push_back({MiddleIntervalStart, MiddleIntervalEnd});
16101
16102 // Compute the partially occupied first byte's interval, if any, counting
16103 // from the MSB.
16104 if (Start != MiddleIntervalStart) {
16105 const uint64_t Length = MiddleIntervalStart - Start;
16106 OccuppiedIntervals.push_back({ByteStart, ByteStart + Length});
16107 }
16108
16109 // Compute the partially occupied last byte's interval, if any, counting
16110 // from the MSB.
16111 if (End != MiddleIntervalEnd) {
16112 const uint64_t Length = End - MiddleIntervalEnd;
16113 OccuppiedIntervals.push_back({ByteEnd - Length, ByteEnd});
16114 }
16115 }
16116
16117 void VisitComplex(const ComplexType *CT, uint64_t StartBitOffset) {
16118 QualType ElementQualType = CT->getElementType().getCanonicalType();
16119 auto ElementSize = Ctx.getTypeSizeInChars(ElementQualType);
16120 auto ElementAlign = Ctx.getTypeAlignInChars(ElementQualType);
16121 auto ImgOffset = ElementSize.alignTo(ElementAlign);
16122
16123 Stack.push_back(
16124 Data{StartBitOffset, ElementQualType, /*VisitVirtualBase*/ true});
16125 Stack.push_back(
16126 Data{StartBitOffset + ImgOffset.getQuantity() * Ctx.getCharWidth(),
16127 ElementQualType, /*VisitVirtualBase*/ true});
16128 }
16129
16130 void VisitVector(const clang::VectorType *VT, uint64_t StartBitOffset) {
16131 if (VT->isPackedVectorBoolType(Ctx)) {
16132 VisitPackedBooleanVector(VT, StartBitOffset);
16133 return;
16134 }
16135
16136 uint64_t SizeBit = getScalarOccupiedSizeInBits(VT->getElementType()) *
16137 VT->getNumElements();
16138 OccuppiedIntervals.push_back(
16139 ASTContext::BitInterval{StartBitOffset, StartBitOffset + SizeBit});
16140 }
16141
16142 /// Compute the occupied bit intervals for a BitInt.
16143 ///
16144 /// In the case of little endian, the occupied bits are always contiguous so a
16145 /// single interval is sufficient. However in big endian, the intervals can be
16146 /// disjoint.
16147 void VisitBitInt(const BitIntType *Ty, uint64_t StartBitOffset) {
16148 const uint64_t OccupiedSizeInBits = Ty->getNumBits();
16149
16150 if (Ctx.getTargetInfo().isLittleEndian()) {
16151 OccuppiedIntervals.push_back(
16152 {StartBitOffset, StartBitOffset + OccupiedSizeInBits});
16153 return;
16154 }
16155
16156 // In big endian mode, the layout of a BitInt in memory has its bytes in
16157 // reverse order, and is pictured in this order:
16158 // 1. Fully padding bytes.
16159 // 2. One partially occupied byte, with padding at the most significant
16160 // bits. ("remaining occupied bits")
16161 // 3. A sequence of fully occupied bytes up until the end of the storage.
16162 const uint64_t StorageSizeInBits = Ctx.getTypeSize(Ty);
16163 const uint64_t CharWidth = Ctx.getCharWidth();
16164 const uint64_t NumFullyPaddingBytes =
16165 (StorageSizeInBits - OccupiedSizeInBits) / CharWidth;
16166 const uint64_t NumFullyOccupiedBytes = OccupiedSizeInBits / CharWidth;
16167 const uint64_t NumRemainingOccupiedBits = OccupiedSizeInBits % CharWidth;
16168
16169 // Partially occupied byte
16170 if (NumRemainingOccupiedBits > 0)
16171 OccuppiedIntervals.push_back(
16172 {StartBitOffset + NumFullyPaddingBytes * CharWidth,
16173 StartBitOffset + NumFullyPaddingBytes * CharWidth +
16174 NumRemainingOccupiedBits});
16175
16176 // Fully occupied bytes
16177 if (NumFullyOccupiedBytes > 0)
16178 OccuppiedIntervals.push_back({StartBitOffset + StorageSizeInBits -
16179 NumFullyOccupiedBytes * CharWidth,
16180 StartBitOffset + StorageSizeInBits});
16181 }
16182
16183 void VisitPackedBooleanVector(const VectorType *VTy,
16184 uint64_t StartBitOffset) {
16185 const uint64_t CharWidth = Ctx.getCharWidth();
16186 assert(StartBitOffset % CharWidth == 0 &&
16187 "Expected aligned packed boolean vector");
16188 assert(VTy->isPackedVectorBoolType(Ctx));
16189 const uint64_t OccupiedSizeInBits = VTy->getNumElements();
16190
16191 if (Ctx.getTargetInfo().isLittleEndian()) {
16192 OccuppiedIntervals.push_back(
16193 {StartBitOffset, StartBitOffset + OccupiedSizeInBits});
16194 return;
16195 }
16196
16197 // Only the sequence of bytes containing occupied bits has its order
16198 // reversed, but the bits within each byte are still counted from the least
16199 // significant bit. So if there are fully padding bytes, they reside at the
16200 // higher addresses in both endiannesses.
16201 const uint64_t NumFullyOccupiedBytes = OccupiedSizeInBits / CharWidth;
16202 const uint64_t NumRemainingOccupiedBits = OccupiedSizeInBits % CharWidth;
16203
16204 uint64_t Start = StartBitOffset;
16205 // Partially occupied byte at the beginning
16206 if (NumRemainingOccupiedBits > 0) {
16207 const uint64_t ByteEnd = Start + CharWidth;
16208 OccuppiedIntervals.push_back({Start, Start + NumRemainingOccupiedBits});
16209 Start = ByteEnd;
16210 }
16211
16212 // The remaining fully occupied bytes form a contiguous interval
16213 if (NumFullyOccupiedBytes > 0) {
16214 OccuppiedIntervals.push_back(
16215 {Start, Start + NumFullyOccupiedBytes * CharWidth});
16216 }
16217 }
16218
16219 void MergeOccuppiedIntervals() {
16220 std::sort(OccuppiedIntervals.begin(), OccuppiedIntervals.end(),
16221 [](const ASTContext::BitInterval &lhs,
16222 const ASTContext::BitInterval &rhs) {
16223 return std::tie(lhs.First, lhs.Last) <
16224 std::tie(rhs.First, rhs.Last);
16225 });
16226
16227 llvm::SmallVector<ASTContext::BitInterval> Merged;
16228 Merged.reserve(OccuppiedIntervals.size());
16229
16230 for (const ASTContext::BitInterval &NextInterval : OccuppiedIntervals) {
16231 if (Merged.empty()) {
16232 Merged.push_back(NextInterval);
16233 continue;
16234 }
16235 auto &LastInterval = Merged.back();
16236
16237 if (NextInterval.First > LastInterval.Last) {
16238 Merged.push_back(NextInterval);
16239 } else {
16240 LastInterval.Last = std::max(LastInterval.Last, NextInterval.Last);
16241 }
16242 }
16243
16244 OccuppiedIntervals = Merged;
16245 }
16246
16247 const ASTContext &Ctx;
16248 // unsigned PointerSizeInBits;
16249 uint64_t TySizeInBits = 0;
16250 llvm::SmallVector<Data> Stack;
16251 llvm::SmallVector<ASTContext::BitInterval> OccuppiedIntervals;
16252};
16253} // namespace
16254
16255llvm::ArrayRef<ASTContext::BitInterval>
16257 Ty = Ty.getCanonicalType();
16258 auto cached = PaddingIntervalCache.find(Ty);
16259 if (cached != PaddingIntervalCache.end())
16260 return cached->second;
16261
16262 PaddingCalculator pc{*this};
16263 pc.run(Ty);
16264
16265 auto [itr, res] =
16266 PaddingIntervalCache.insert_or_assign(Ty, pc.GetPaddingIntervals());
16267 assert(res && "Failed to insert?");
16268
16269 return itr->second;
16270}
This file provides AST data structures related to concepts.
static void SortAndUniqueProtocols(SmallVectorImpl< ObjCProtocolDecl * > &Protocols)
static bool isCanonicalExceptionSpecification(const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType)
static SourceLocation getCommonAttrLoc(const T *X, const T *Y)
static auto getCanonicalTemplateArguments(const ASTContext &C, ArrayRef< TemplateArgument > Args, bool &AnyNonCanonArgs)
static char getObjCEncodingForPrimitiveType(const ASTContext *C, const BuiltinType *BT)
static bool isSameQualifier(const NestedNameSpecifier X, const NestedNameSpecifier Y)
static bool unionHasUniqueObjectRepresentations(const ASTContext &Context, const RecordDecl *RD, bool CheckIfTriviallyCopyable)
static TypedefDecl * CreateHexagonBuiltinVaListDecl(const ASTContext *Context)
#define CANONICAL_TYPE(Class)
static ElaboratedTypeKeyword getCommonTypeKeyword(const T *X, const T *Y, bool IsSame)
static Decl * getCommonDecl(Decl *X, Decl *Y)
static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context, const Decl *D, GVALinkage L)
static bool isTypeTypedefedAsBOOL(QualType T)
static void EncodeBitField(const ASTContext *Ctx, std::string &S, QualType T, const FieldDecl *FD)
static GVALinkage basicGVALinkageForVariable(const ASTContext &Context, const VarDecl *VD)
static QualType getCommonArrayElementType(const ASTContext &Ctx, const T *X, Qualifiers &QX, const T *Y, Qualifiers &QY)
static bool hasImplicitAttr(const ValueDecl *D)
#define SUGAR_FREE_TYPE(Class)
static SYCLKernelInfo BuildSYCLKernelInfo(ASTContext &Context, CanQualType KernelNameType, const FunctionDecl *FD)
static bool hasTemplateSpecializationInEncodedString(const Type *T, bool VisitBasesAndFields)
static void getIntersectionOfProtocols(ASTContext &Context, const ObjCInterfaceDecl *CommonBase, const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT, SmallVectorImpl< ObjCProtocolDecl * > &IntersectionSet)
getIntersectionOfProtocols - This routine finds the intersection of set of protocols inherited from t...
static bool areCompatMatrixTypes(const ConstantMatrixType *LHS, const ConstantMatrixType *RHS)
areCompatMatrixTypes - Return true if the two specified matrix types are compatible.
static TypedefDecl * CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context)
static bool sameObjCTypeArgs(ASTContext &ctx, const ObjCInterfaceDecl *iface, ArrayRef< QualType > lhsArgs, ArrayRef< QualType > rhsArgs, bool stripKindOf)
static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs, QualType rhs)
Determine whether the first type is a subtype of the second.
static const Type * getIntegerTypeForEnum(const EnumType *ET)
static SmallVector< SourceLocation, 2 > getLocsForCommentSearch(ASTContext::RawCommentLookupKey Key, SourceManager &SourceMgr)
static bool hasSameCudaAttrs(const FunctionDecl *A, const FunctionDecl *B)
static TemplateName getCommonTemplateName(const ASTContext &Ctx, TemplateName X, TemplateName Y, bool IgnoreDeduced=false)
static int CmpProtocolNames(ObjCProtocolDecl *const *LHS, ObjCProtocolDecl *const *RHS)
CmpProtocolNames - Comparison predicate for sorting protocols alphabetically.
static auto * getCommonSizeExpr(const ASTContext &Ctx, T *X, T *Y)
static TypedefDecl * CreatePowerABIBuiltinVaListDecl(const ASTContext *Context)
static auto getCommonSizeModifier(const ArrayType *X, const ArrayType *Y)
static TemplateArgument getCommonTemplateArgument(const ASTContext &Ctx, const TemplateArgument &X, const TemplateArgument &Y)
static std::optional< int64_t > structHasUniqueObjectRepresentations(const ASTContext &Context, const RecordDecl *RD, bool CheckIfTriviallyCopyable)
static bool hasSameOverloadableAttrs(const FunctionDecl *A, const FunctionDecl *B)
Determine whether the attributes we can overload on are identical for A and B.
static T * getCommonDeclChecked(T *X, T *Y)
static NestedNameSpecifier getCommonNNS(const ASTContext &Ctx, NestedNameSpecifier NNS1, NestedNameSpecifier NNS2, bool IsSame)
Returns a NestedNameSpecifier which has only the common sugar present in both NNS1 and NNS2.
static TypedefDecl * CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context)
static int64_t getSubobjectOffset(const FieldDecl *Field, const ASTContext &Context, const clang::ASTRecordLayout &)
static QualType getCommonSugarTypeNode(const ASTContext &Ctx, const Type *X, const Type *Y, SplitQualType Underlying)
static TypedefDecl * CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context)
static QualType getCommonNonSugarTypeNode(const ASTContext &Ctx, const Type *X, Qualifiers &QX, const Type *Y, Qualifiers &QY)
static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET, QualType other, bool isBlockReturnType)
Given that we have an enum type and a non-enum type, try to merge them.
static GVALinkage adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D, GVALinkage L)
Adjust the GVALinkage for a declaration based on what an external AST source knows about whether ther...
static TypedefDecl * CreateSystemZBuiltinVaListDecl(const ASTContext *Context)
static std::optional< int64_t > getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context, bool CheckIfTriviallyCopyable)
static GVALinkage basicGVALinkageForFunction(const ASTContext &Context, const FunctionDecl *FD)
#define NON_UNIQUE_TYPE(Class)
static TypedefDecl * CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context)
static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI, const LangOptions &LangOpts)
static ElaboratedTypeKeyword getCanonicalElaboratedTypeKeyword(ElaboratedTypeKeyword Keyword)
static QualType getCommonPointeeType(const ASTContext &Ctx, const T *X, const T *Y)
static auto getCommonIndexTypeCVRQualifiers(const ArrayType *X, const ArrayType *Y)
static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context, ASTContext::GetBuiltinTypeError &Error, bool &RequiresICE, bool AllowTypeModifiers)
DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the pointer over the consume...
FloatingRank
@ FloatRank
@ LongDoubleRank
@ Float16Rank
@ Ibm128Rank
@ Float128Rank
@ BFloat16Rank
@ HalfRank
@ DoubleRank
static TypedefDecl * CreateCharPtrBuiltinVaListDecl(const ASTContext *Context)
static bool areSortedAndUniqued(ArrayRef< ObjCProtocolDecl * > Protocols)
static TypeInfoChars getConstantArrayInfoInChars(const ASTContext &Context, const ConstantArrayType *CAT)
getConstantArrayInfoInChars - Performing the computation in CharUnits instead of in bits prevents ove...
static FloatingRank getFloatingRank(QualType T)
getFloatingRank - Return a relative rank for floating point types.
static bool getCommonTemplateArguments(const ASTContext &Ctx, SmallVectorImpl< TemplateArgument > &R, ArrayRef< TemplateArgument > Xs, ArrayRef< TemplateArgument > Ys)
static TypedefDecl * CreateXtensaABIBuiltinVaListDecl(const ASTContext *Context)
static QualType getCommonElementType(const ASTContext &Ctx, const T *X, const T *Y)
static void mergeTypeLists(const ASTContext &Ctx, SmallVectorImpl< QualType > &Out, ArrayRef< QualType > X, ArrayRef< QualType > Y)
static bool matchesPostDecrInWhile(const UnaryOperator *UO, ASTContext &Ctx)
For the purposes of overflow pattern exclusion, does this match the while(i–) pattern?
static void encodeTypeForFunctionPointerAuth(const ASTContext &Ctx, raw_ostream &OS, QualType QT)
Encode a function type for use in the discriminator of a function pointer type.
static std::optional< int64_t > structSubobjectsHaveUniqueObjectRepresentations(const RangeT &Subobjects, int64_t CurOffsetInBits, const ASTContext &Context, const clang::ASTRecordLayout &Layout, bool CheckIfTriviallyCopyable)
static uint64_t getRVVTypeSize(ASTContext &Context, const BuiltinType *Ty)
getRVVTypeSize - Return RVV vector register size.
static auto unwrapSugar(SplitQualType &T, Qualifiers &QTotal)
static TemplateName getCommonTemplateNameChecked(const ASTContext &Ctx, TemplateName X, TemplateName Y, bool IgnoreDeduced)
static int compareObjCProtocolsByName(ObjCProtocolDecl *const *lhs, ObjCProtocolDecl *const *rhs)
Comparison routine for Objective-C protocols to be used with llvm::array_pod_sort.
static const TagDecl * getNonInjectedClassName(const TagDecl *TD)
static TypedefDecl * CreateZOSVaListDecl(const ASTContext *Context)
static bool hasAnyPackExpansions(ArrayRef< TemplateArgument > Args)
static char ObjCEncodingForEnumDecl(const ASTContext *C, const EnumDecl *ED)
static std::string charUnitsToString(CharUnits CU)
static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod, SmallVectorImpl< const NamedDecl * > &Redeclared)
static QualType getCommonTypeWithQualifierLifting(const ASTContext &Ctx, QualType X, QualType Y, Qualifiers &QX, Qualifiers &QY)
static auto getCommonTypes(const ASTContext &Ctx, ArrayRef< QualType > Xs, ArrayRef< QualType > Ys, bool Unqualified=false)
static bool isCanonicalResultType(QualType T)
Determine whether T is canonical as the result type of a function.
static TypedefDecl * CreateMSVaListDecl(const ASTContext *Context)
static bool areCompatVectorTypes(const VectorType *LHS, const VectorType *RHS)
areCompatVectorTypes - Return true if the two specified vector types are compatible.
static TypedefDecl * CreateCharPtrNamedVaListDecl(const ASTContext *Context, StringRef Name)
static NestedNameSpecifier getCommonQualifier(const ASTContext &Ctx, const T *X, const T *Y, bool IsSame)
#define UNEXPECTED_TYPE(Class, Kind)
static TypedefDecl * CreateVaListDecl(const ASTContext *Context, TargetInfo::BuiltinVaListKind Kind)
static bool primaryBaseHaseAddressDiscriminatedVTableAuthentication(const ASTContext &Context, const CXXRecordDecl *Class)
static std::vector< std::string > getFMVBackendFeaturesFor(const llvm::SmallVectorImpl< StringRef > &FMVFeatStrings)
Defines the clang::ASTContext interface.
#define V(N, I)
#define BuiltinTemplate(BTName)
Definition ASTContext.h:504
This file provides some common utility functions for processing Lambda related AST Constructs.
Provides definitions for the various language-specific address spaces.
static bool isUnsigned(SValBuilder &SVB, NonLoc Value)
Defines enum values for all the target-independent builtin functions.
static bool CanThrow(Expr *E, ASTContext &Ctx)
Definition CFG.cpp:2822
Defines the clang::CommentOptions interface.
static Decl::Kind getKind(const Decl *D)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
This file defines OpenMP nodes for declarative directives.
Defines the C++ template declaration subclasses.
Defines the ExceptionSpecificationType enumeration and various utility functions.
Defines the clang::Expr interface and subclasses for C++ expressions.
FormatToken * Next
The next token in the unwrapped line.
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
static const Decl * getCanonicalDecl(const Decl *D)
#define X(type, name)
Definition Value.h:97
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::LangOptions interface.
llvm::MachO::Target Target
Definition MachO.h:51
llvm::MachO::Record Record
Definition MachO.h:31
Defines the clang::MacroInfo and clang::MacroDirective classes.
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:96
Defines the clang::Module class, which describes a module in the source code.
static StringRef getTriple(const Command &Job)
Defines types useful for describing an Objective-C runtime.
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a kind
static bool compare(const PathDiagnostic &X, const PathDiagnostic &Y)
static QualType getUnderlyingType(const SubRegion *R)
Defines the clang::SourceLocation class and associated facilities.
Defines the SourceManager interface.
Defines various enumerations that describe declaration and type specifiers.
static QualType getPointeeType(const MemRegion *R)
Defines the TargetCXXABI class, which abstracts details of the C++ ABI that we're targeting.
Defines the clang::TypeLoc interface and its subclasses.
C Language Family Type Representation.
QualType getReadPipeType(QualType T) const
Return a read_only pipe type for the specified type.
llvm::PointerUnion< const Decl *, const MacroInfo * > RawCommentLookupKey
Key used to look up the raw comment attached to a declaration or macro.
RawComment * getRawCommentNoCacheImpl(RawCommentLookupKey Key, const SourceLocation RepresentativeLoc, const std::map< unsigned, RawComment * > &CommentsInFile) const
QualType getWritePipeType(QualType T) const
Return a write_only pipe type for the specified type.
@ GE_Missing_stdio
Missing a type from <stdio.h>
@ GE_Missing_ucontext
Missing a type from <ucontext.h>
@ GE_Missing_setjmp
Missing a type from <setjmp.h>
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:158
bool isMemberPointerToDerivedMember() const
Definition APValue.cpp:1227
const ValueDecl * getMemberPointerDecl() const
Definition APValue.cpp:1220
ArrayRef< const CXXRecordDecl * > getMemberPointerPath() const
Definition APValue.cpp:1234
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:245
bool getByrefLifetime(QualType Ty, Qualifiers::ObjCLifetime &Lifetime, bool &HasByrefExtendedLayout) const
Returns true, if given type has a known lifetime.
MSGuidDecl * getMSGuidDecl(MSGuidDeclParts Parts) const
Return a declaration for the global GUID object representing the given GUID value.
CanQualType AccumTy
BuiltinVectorTypeInfo getBuiltinVectorTypeInfo(const BuiltinType *VecTy) const
Returns the element type, element count and number of vectors (in case of tuple) for a builtin vector...
bool ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl, const ObjCMethodDecl *MethodImp)
CanQualType ObjCBuiltinSelTy
TranslationUnitDecl * getTranslationUnitDecl() const
const ConstantArrayType * getAsConstantArrayType(QualType T) const
CanQualType getCanonicalFunctionResultType(QualType ResultType) const
Adjust the given function result type.
QualType getAtomicType(QualType T) const
Return the uniqued reference to the atomic type for the specified type.
LangAS getOpenCLTypeAddrSpace(const Type *T) const
Get address space for OpenCL type.
const llvm::StringMap< bool > & getFunctionFeatureMap(const FunctionDecl *FD) const
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.
QualType getParenType(QualType NamedType) const
size_t getSideTableAllocatedMemory() const
Return the total memory used for various side tables.
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type.
CanQualType ARCUnbridgedCastTy
QualType getDependentSizedMatrixType(QualType ElementType, Expr *RowExpr, Expr *ColumnExpr, SourceLocation AttrLoc) const
Return the unique reference to the matrix type of the specified element type and size.
QualType getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr, QualType Wrapped) const
llvm::DenseMap< const Decl *, comments::FullComment * > ParsedComments
Mapping from declarations to parsed comments attached to any redeclaration.
unsigned getManglingNumber(const NamedDecl *ND, bool ForAuxTarget=false) const
CanQualType LongTy
unsigned getIntWidth(QualType T) const
CanQualType getCanonicalParamType(QualType T) const
Return the canonical parameter type corresponding to the specific potentially non-canonical one.
const FunctionType * adjustFunctionType(const FunctionType *Fn, FunctionType::ExtInfo EInfo)
Change the ExtInfo on a function type.
TemplateOrSpecializationInfo getTemplateOrSpecializationInfo(const VarDecl *Var)
CanQualType WIntTy
@ Weak
Weak definition of inline variable.
@ WeakUnknown
Weak for now, might become strong later in this TU.
bool dtorHasOperatorDelete(const CXXDestructorDecl *Dtor, OperatorDeleteKind K) const
void setObjCConstantStringInterface(ObjCInterfaceDecl *Decl)
TypedefDecl * getObjCClassDecl() const
Retrieve the typedef declaration corresponding to the predefined Objective-C 'Class' type.
TypedefNameDecl * getTypedefNameForUnnamedTagDecl(const TagDecl *TD)
TypedefDecl * getCFConstantStringDecl() const
CanQualType Int128Ty
CanQualType SatUnsignedFractTy
void setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern)
Remember that the using decl Inst is an instantiation of the using decl Pattern of a class template.
bool areCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given types are an RISC-V vector builtin type and a VectorType that is a fixed-len...
QualType getConstantMatrixType(QualType ElementType, unsigned NumRows, unsigned NumColumns, std::optional< MatrixType::LayoutKind > Layout=std::nullopt) const
Return the unique reference to the matrix type of the specified element type and size.
ExternCContextDecl * getExternCContextDecl() const
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
ParsedTargetAttr filterFunctionTargetAttrs(const TargetAttr *TD) const
Parses the target attributes passed in, and returns only the ones that are valid feature names.
QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT)
TypedefDecl * getObjCSelDecl() const
Retrieve the typedef corresponding to the predefined 'SEL' type in Objective-C.
CanQualType UnsignedShortAccumTy
TypedefDecl * getObjCInstanceTypeDecl()
Retrieve the typedef declaration corresponding to the Objective-C "instancetype" type.
QualType adjustFunctionResultType(QualType FunctionType, QualType NewResultType)
Change the result type of a function type, preserving sugar such as attributed types.
void setTemplateOrSpecializationInfo(VarDecl *Inst, TemplateOrSpecializationInfo TSI)
bool isTypeAwareOperatorNewOrDelete(const FunctionDecl *FD) const
bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto, ObjCProtocolDecl *rProto) const
ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the inheritance hierarchy of 'rProto...
TypedefDecl * buildImplicitTypedef(QualType T, StringRef Name) const
Create a new implicit TU-level typedef declaration.
QualType getCanonicalTemplateSpecializationType(ElaboratedTypeKeyword Keyword, TemplateName T, ArrayRef< TemplateArgument > CanonicalArgs) const
QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl, ObjCInterfaceDecl *PrevDecl=nullptr) const
getObjCInterfaceType - Return the unique reference to the type for the specified ObjC interface decl.
void adjustObjCTypeParamBoundType(const ObjCTypeParamDecl *Orig, ObjCTypeParamDecl *New) const
QualType getAutoType(DeducedKind DK, QualType DeducedAsType, AutoTypeKeyword Keyword, TemplateName TypeConstraintConcept=TemplateName(), ArrayRef< TemplateArgument > TypeConstraintArgs={}) const
C++11 deduced auto type.
QualType getBlockPointerType(QualType T) const
Return the uniqued reference to the type for a block of the specified type.
TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg) const
Retrieve the "canonical" template argument.
QualType getAutoRRefDeductType() const
C++11 deduction pattern for 'auto &&' type.
TypedefDecl * getBuiltinMSVaListDecl() const
Retrieve the C type declaration corresponding to the predefined __builtin_ms_va_list type.
bool ObjCQualifiedIdTypesAreCompatible(const ObjCObjectPointerType *LHS, const ObjCObjectPointerType *RHS, bool ForCompare)
ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an ObjCQualifiedIDType.
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
QualType mergeFunctionTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false, bool AllowCXX=false, bool IsConditionalOperator=false)
NamedDecl * getInstantiatedFromUsingDecl(NamedDecl *Inst)
If the given using decl Inst is an instantiation of another (possibly unresolved) using decl,...
DeclarationNameTable DeclarationNames
Definition ASTContext.h:859
comments::FullComment * cloneFullComment(comments::FullComment *FC, const Decl *D) const
CharUnits getObjCEncodingTypeSize(QualType T) const
Return the size of type T for Objective-C encoding purpose, in characters.
int getIntegerTypeOrder(QualType LHS, QualType RHS) const
Return the highest ranked integer type, see C99 6.3.1.8p1.
const TemplateArgument * getDefaultTemplateArgumentOrNone(const NamedDecl *P) const
Return the default argument of a template parameter, if one exists.
QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType, const Attr *attr=nullptr) const
TypedefDecl * getObjCIdDecl() const
Retrieve the typedef corresponding to the predefined id type in Objective-C.
void setCurrentNamedModule(Module *M)
Set the (C++20) module we are building.
QualType getProcessIDType() const
Return the unique type for "pid_t" defined in <sys/types.h>.
CharUnits getMemberPointerPathAdjustment(const APValue &MP) const
Find the 'this' offset for the member path in a pointer-to-member APValue.
bool mayExternalize(const Decl *D) const
Whether a C++ static variable or CUDA/HIP kernel may be externalized.
std::unique_ptr< MangleNumberingContext > createMangleNumberingContext() const
CanQualType SatAccumTy
ArrayRef< CXXDefaultArgExpr * > getCtorClosureDefaultArgs(const CXXConstructorDecl *CD)
QualType getUnsignedPointerDiffType() const
Return the unique unsigned counterpart of "ptrdiff_t" integer type.
QualType getScalableVectorType(QualType EltTy, unsigned NumElts, unsigned NumFields=1) const
Return the unique reference to a scalable vector type of the specified element type and scalable numb...
bool hasSameExpr(const Expr *X, const Expr *Y) const
Determine whether the given expressions X and Y are equivalent.
TemplateName getPackIndexingTemplateName(TemplateName Pattern, Expr *IndexExpr, bool FullySubstituted=false, ArrayRef< TemplateName > Expansions={}) const
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.
RawComment * getRawCommentNoCache(RawCommentLookupKey Key) const
Return the documentation comment attached to a given declaration or macro, without looking into cache...
QualType getRealTypeForBitwidth(unsigned DestWidth, FloatModeKind ExplicitType) const
getRealTypeForBitwidth - sets floating point QualTy according to specified bitwidth.
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like 'int()'.
CanQualType ShortAccumTy
ASTMutationListener * getASTMutationListener() const
Retrieve a pointer to the AST mutation listener associated with this AST context, if any.
unsigned NumImplicitCopyAssignmentOperatorsDeclared
The number of implicitly-declared copy assignment operators for which declarations were built.
uint64_t getTargetNullPointerValue(QualType QT) const
Get target-dependent integer value for null pointer which is used for constant folding.
unsigned getTypeUnadjustedAlign(QualType T) const
Return the ABI-specified natural alignment of a (complete) type T, before alignment adjustments,...
unsigned char getFixedPointIBits(QualType Ty) const
QualType getSubstBuiltinTemplatePack(const TemplateArgument &ArgPack)
QualType getCorrespondingSignedFixedPointType(QualType Ty) const
IntrusiveRefCntPtr< ExternalASTSource > ExternalSource
Definition ASTContext.h:860
CanQualType FloatTy
QualType getArrayParameterType(QualType Ty) const
Return the uniqued reference to a specified array parameter type from the original array type.
QualType getCountAttributedType(QualType T, Expr *CountExpr, bool CountInBytes, bool OrNull, ArrayRef< TypeCoupledDeclRefInfo > DependentDecls) const
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
unsigned NumImplicitDestructorsDeclared
The number of implicitly-declared destructors for which declarations were built.
bool mergeExtParameterInfo(const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType, bool &CanUseFirst, bool &CanUseSecond, SmallVectorImpl< FunctionProtoType::ExtParameterInfo > &NewParamInfos)
This function merges the ExtParameterInfo lists of two functions.
bool ObjCQualifiedClassTypesAreCompatible(const ObjCObjectPointerType *LHS, const ObjCObjectPointerType *RHS)
ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and Class<pr1, ...>.
bool shouldExternalize(const Decl *D) const
Whether a C++ static variable or CUDA/HIP kernel should be externalized.
bool propertyTypesAreCompatible(QualType, QualType)
void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst, UsingShadowDecl *Pattern)
CanQualType DoubleTy
QualType getDependentVectorType(QualType VectorType, Expr *SizeExpr, SourceLocation AttrLoc, VectorKind VecKind) const
Return the unique reference to the type for a dependently sized vector of the specified element type.
CanQualType SatLongAccumTy
CanQualType getIntMaxType() const
Return the unique type for "intmax_t" (C99 7.18.1.5), defined in <stdint.h>.
QualType getVectorType(QualType VectorType, unsigned NumElts, VectorKind VecKind) const
Return the unique reference to a vector type of the specified element type and size.
OpenCLTypeKind getOpenCLTypeKind(const Type *T) const
Map an AST Type to an OpenCLTypeKind enum value.
TemplateName getDependentTemplateName(const DependentTemplateStorage &Name) const
Retrieve the template name that represents a dependent template name such as MetaFun::template operat...
ArrayRef< Decl * > getModuleInitializers(Module *M)
Get the initializations to perform when importing a module, if any.
void getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT, std::string &S) const
Put the string version of the type qualifiers QT into S.
unsigned getPreferredTypeAlign(QualType T) const
Return the "preferred" alignment of the specified type T for the current target, in bits.
std::string getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, bool Extended=false) const
Emit the encoded type for the method declaration Decl into S.
bool DeclMustBeEmitted(const Decl *D)
Determines if the decl can be CodeGen'ed or deserialized from PCH lazily, only when used; this is onl...
CanQualType LongDoubleTy
CanQualType OMPArrayShapingTy
ASTContext(LangOptions &LOpts, SourceManager &SM, IdentifierTable &idents, SelectorTable &sels, Builtin::Context &builtins, TranslationUnitKind TUKind)
QualType getReadPipeType(QualType T) const
Return a read_only pipe type for the specified type.
std::string getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, const Decl *Container) const
getObjCEncodingForPropertyDecl - Return the encoded type for this method declaration.
CanQualType Char16Ty
TemplateName getCanonicalTemplateName(TemplateName Name, bool IgnoreDeduced=false) const
Retrieves the "canonical" template name that refers to a given template.
unsigned getStaticLocalNumber(const VarDecl *VD) const
void addComment(const RawComment &RC)
void getLegacyIntegralTypeEncoding(QualType &t) const
getLegacyIntegralTypeEncoding - Another legacy compatibility encoding: 32-bit longs are encoded as 'l...
bool isSameTypeConstraint(const TypeConstraint *XTC, const TypeConstraint *YTC) const
Determine whether two type contraint are similar enough that they could used in declarations of the s...
void setRelocationInfoForCXXRecord(const CXXRecordDecl *, CXXRecordDeclRelocationInfo)
QualType getSubstTemplateTypeParmType(QualType Replacement, Decl *AssociatedDecl, unsigned Index, UnsignedOrNone PackIndex, bool Final) const
Retrieve a substitution-result type.
RecordDecl * buildImplicitRecord(StringRef Name, RecordDecl::TagKind TK=RecordDecl::TagKind::Struct) const
Create a new implicit TU-level CXXRecordDecl or RecordDecl declaration.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
const CXXMethodDecl * getCurrentKeyFunction(const CXXRecordDecl *RD)
Get our current best idea for the key function of the given record decl, or nullptr if there isn't on...
void completeCountAttributedType(CountAttributedType *CATy, Expr *CountExpr, ArrayRef< TypeCoupledDeclRefInfo > DependentDecls) const
Supply the count expression and coupled declarations for a type created by getIncompleteCountAttribut...
CanQualType UnsignedLongFractTy
QualType mergeTagDefinitions(QualType, QualType)
void setClassMaybeNeedsVectorDeletingDestructor(const CXXRecordDecl *RD)
overridden_method_range overridden_methods(const CXXMethodDecl *Method) const
void setIsTypeAwareOperatorNewOrDelete(const FunctionDecl *FD, bool IsTypeAware)
QualType getDependentBitIntType(bool Unsigned, Expr *BitsExpr) const
Return a dependent bit-precise integer type with the specified signedness and bit count.
void setObjCImplementation(ObjCInterfaceDecl *IFaceD, ObjCImplementationDecl *ImplD)
Set the implementation of ObjCInterfaceDecl.
StringRef getCUIDHash() const
bool isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const
Returns true if this is an inline-initialized static data member which is treated as a definition for...
bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT)
canAssignObjCInterfaces - Return true if the two interface types are compatible for assignment from R...
CanQualType VoidPtrTy
QualType getReferenceQualifiedType(const Expr *e) const
getReferenceQualifiedType - Given an expr, will return the type for that expression,...
bool hasSameFunctionTypeIgnoringExceptionSpec(QualType T, QualType U) const
Determine whether two function types are the same, ignoring exception specifications in cases where t...
QualType getBlockDescriptorExtendedType() const
Gets the struct used to keep track of the extended descriptor for pointer to blocks.
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
CanQualType DependentTy
bool QIdProtocolsAdoptObjCObjectProtocols(QualType QT, ObjCInterfaceDecl *IDecl)
QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in QT's qualified-id protocol list adopt...
FunctionProtoType::ExceptionSpecInfo mergeExceptionSpecs(FunctionProtoType::ExceptionSpecInfo ESI1, FunctionProtoType::ExceptionSpecInfo ESI2, SmallVectorImpl< QualType > &ExceptionTypeStorage, bool AcceptDependent) const
llvm::PointerUnion< const Decl *, const MacroInfo * > RawCommentLookupKey
Key used to look up the raw comment attached to a declaration or macro.
void addLazyModuleInitializers(Module *M, ArrayRef< GlobalDeclID > IDs)
bool isSameConstraintExpr(const Expr *XCE, const Expr *YCE) const
Determine whether two 'requires' expressions are similar enough that they may be used in re-declarati...
bool BlockRequiresCopying(QualType Ty, const VarDecl *D)
Returns true iff we need copy/dispose helpers for the given type.
CanQualType NullPtrTy
QualType getUsingType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const UsingShadowDecl *D, QualType UnderlyingType=QualType()) const
std::optional< QualType > tryMergeOverflowBehaviorTypes(QualType LHS, QualType RHS, bool OfBlockPointer, bool Unqualified, bool BlockReturnType, bool IsConditionalOperator)
Attempts to merge two types that may be OverflowBehaviorTypes.
CanQualType WideCharTy
CanQualType OMPIteratorTy
IdentifierTable & Idents
Definition ASTContext.h:855
Builtin::Context & BuiltinInfo
Definition ASTContext.h:857
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
QualType getFunctionTypeWithoutPtrSizes(QualType T)
Get a function type and produce the equivalent function type where pointer size address spaces in the...
uint64_t lookupFieldBitOffset(const ObjCInterfaceDecl *OID, const ObjCIvarDecl *Ivar) const
Get the offset of an ObjCIvarDecl in bits.
SelectorTable & Selectors
Definition ASTContext.h:856
bool isTypeIgnoredBySanitizer(const SanitizerMask &Mask, const QualType &Ty) const
Check if a type can have its sanitizer instrumentation elided based on its presence within an ignorel...
unsigned getMinGlobalAlignOfVar(uint64_t Size, const VarDecl *VD) const
Return the minimum alignment as specified by the target.
RawCommentList Comments
All comments in this translation unit.
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 getLateParsedAttrType(QualType Wrapped, LateParsedTypeAttribute *LateParsedAttr) const
Return a placeholder type for a late-parsed type attribute.
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...
llvm::ArrayRef< BitInterval > getPaddingIntervals(QualType Ty) const
CanQualType SatShortFractTy
QualType getDecayedType(QualType T) const
Return the uniqued reference to the decayed version of the given type.
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod) const
Retrieves the default calling convention for the current context.
bool canBindObjCObjectType(QualType To, QualType From)
TemplateTemplateParmDecl * insertCanonicalTemplateTemplateParmDeclInternal(TemplateTemplateParmDecl *CanonTTP) const
int getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const
Compare the rank of two floating point types as above, but compare equal if both types have the same ...
QualType getUIntPtrType() const
Return a type compatible with "uintptr_t" (C99 7.18.1.4), as defined by the target.
void setParameterIndex(const ParmVarDecl *D, unsigned index)
Used by ParmVarDecl to store on the side the index of the parameter when it exceeds the size of the n...
QualType getFunctionTypeWithExceptionSpec(QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const
Get a function type and produce the equivalent function type with the specified exception specificati...
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier NNS, const IdentifierInfo *Name) const
Qualifiers::GC getObjCGCAttrKind(QualType Ty) const
Return one of the GCNone, Weak or Strong Objective-C garbage collection attributes.
CanQualType Ibm128Ty
bool hasUniqueObjectRepresentations(QualType Ty, bool CheckIfTriviallyCopyable=true) const
Return true if the specified type has unique object representations according to (C++17 [meta....
CanQualType getCanonicalSizeType() const
bool typesAreBlockPointerCompatible(QualType, QualType)
CanQualType SatUnsignedAccumTy
bool useAbbreviatedThunkName(GlobalDecl VirtualMethodDecl, StringRef MangledName)
const ASTRecordLayout & getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const
Get or compute information about the layout of the specified Objective-C interface.
void forEachMultiversionedFunctionVersion(const FunctionDecl *FD, llvm::function_ref< void(FunctionDecl *)> Pred) const
Visits all versions of a multiversioned function with the passed predicate.
void setInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst, UsingEnumDecl *Pattern)
Remember that the using enum decl Inst is an instantiation of the using enum decl Pattern of a class ...
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
llvm::SetVector< const VarDecl * > CUDADeviceVarODRUsedByHost
Keep track of CUDA/HIP device-side variables ODR-used by host code.
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
QualType getSignatureParameterType(QualType T) const
Retrieve the parameter type as adjusted for use in the signature of a function, decaying array and fu...
CanQualType ArraySectionTy
CanQualType ObjCBuiltinIdTy
overridden_cxx_method_iterator overridden_methods_end(const CXXMethodDecl *Method) const
VTableContextBase * getVTableContext()
ComparisonCategories CompCategories
Types and expressions required to build C++2a three-way comparisons using operator<=>,...
int getFloatingTypeOrder(QualType LHS, QualType RHS) const
Compare the rank of the two specified floating point types, ignoring the domain of the type (i....
unsigned CountNonClassIvars(const ObjCInterfaceDecl *OI) const
ObjCPropertyImplDecl * getObjCPropertyImplDeclForPropertyDecl(const ObjCPropertyDecl *PD, const Decl *Container) const
bool isNearlyEmpty(const CXXRecordDecl *RD) const
PointerAuthQualifier getObjCMemberSelTypePtrAuth()
QualType AutoDeductTy
CanQualType BoolTy
void attachCommentsToJustParsedDecls(ArrayRef< Decl * > Decls, const Preprocessor *PP)
Searches existing comments for doc comments that should be attached to Decls.
QualType getIntTypeForBitwidth(unsigned DestWidth, unsigned Signed) const
getIntTypeForBitwidth - sets integer QualTy according to specified details: bitwidth,...
void setStaticLocalNumber(const VarDecl *VD, unsigned Number)
QualType getCFConstantStringType() const
Return the C structure type used to represent constant CFStrings.
UsingEnumDecl * getInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst)
If the given using-enum decl Inst is an instantiation of another using-enum decl, return it.
RecordDecl * getCFConstantStringTagDecl() const
std::string getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const
Emit the encoded type for the function Decl into S.
TypeSourceInfo * getTemplateSpecializationTypeInfo(ElaboratedTypeKeyword Keyword, SourceLocation ElaboratedKeywordLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKeywordLoc, TemplateName T, SourceLocation TLoc, const TemplateArgumentListInfo &SpecifiedArgs, ArrayRef< TemplateArgument > CanonicalArgs, QualType Canon=QualType()) const
CanQualType MetaInfoTy
CanQualType UnsignedFractTy
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
QualType mergeFunctionParameterTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false)
mergeFunctionParameterTypes - merge two types which appear as function parameter types
void addOverriddenMethod(const CXXMethodDecl *Method, const CXXMethodDecl *Overridden)
Note that the given C++ Method overrides the given Overridden method.
TemplateTemplateParmDecl * findCanonicalTemplateTemplateParmDeclInternal(TemplateTemplateParmDecl *TTP) const
const TargetInfo * getAuxTargetInfo() const
Definition ASTContext.h:975
CanQualType Float128Ty
CanQualType ObjCBuiltinClassTy
unsigned NumImplicitDefaultConstructorsDeclared
The number of implicitly-declared default constructors for which declarations were built.
CanQualType UnresolvedTemplateTy
OMPTraitInfo & getNewOMPTraitInfo()
Return a new OMPTraitInfo object owned by this context.
friend class CXXRecordDecl
Definition ASTContext.h:615
CanQualType UnsignedLongTy
llvm::DenseSet< const FunctionDecl * > CUDAImplicitHostDeviceFunUsedByDevice
Keep track of CUDA/HIP implicit host device functions used on device side in device compilation.
void DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, bool leafClass, SmallVectorImpl< const ObjCIvarDecl * > &Ivars) const
DeepCollectObjCIvars - This routine first collects all declared, but not synthesized,...
bool computeBestEnumTypes(bool IsPacked, unsigned NumNegativeBits, unsigned NumPositiveBits, QualType &BestType, QualType &BestPromotionType)
Compute BestType and BestPromotionType for an enum based on the highest number of negative and positi...
llvm::APFixedPoint getFixedPointMin(QualType Ty) const
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
QualType adjustType(QualType OldType, llvm::function_ref< QualType(QualType)> Adjust) const
Rebuild a type, preserving any existing type sugar.
void addedLocalImportDecl(ImportDecl *Import)
Notify the AST context that a new import declaration has been parsed or implicitly created within thi...
const TranslationUnitKind TUKind
Definition ASTContext.h:858
CanQualType UnsignedLongAccumTy
QualType AutoRRefDeductTy
RawComment * getRawCommentNoCacheImpl(RawCommentLookupKey Key, const SourceLocation RepresentativeLoc, const std::map< unsigned, RawComment * > &CommentsInFile) const
CountAttributedType * getIncompleteCountAttributedType(QualType WrappedTy, bool CountInBytes, bool OrNull) const
Return a CountAttributedType whose count expression has not been parsed yet, for use by a late-parsed...
TypeInfo getTypeInfo(const Type *T) const
Get the size and alignment of the specified complete type in bits.
CanQualType ShortFractTy
QualType getStringLiteralArrayType(QualType EltTy, unsigned Length) const
Return a type for a constant array for a string literal of the specified element type and length.
QualType getCorrespondingSaturatedType(QualType Ty) const
bool arePFPFieldsTriviallyCopyable(const RecordDecl *RD) const
Returns whether this record's PFP fields (if any) are trivially copyable (i.e.
bool isSameEntity(const NamedDecl *X, const NamedDecl *Y) const
Determine whether the two declarations refer to the same entity.
QualType getSubstTemplateTypeParmPackType(Decl *AssociatedDecl, unsigned Index, bool Final, const TemplateArgument &ArgPack)
CanQualType BoundMemberTy
CanQualType SatUnsignedShortFractTy
CanQualType CharTy
QualType removeAddrSpaceQualType(QualType T) const
Remove any existing address space on the type and returns the type with qualifiers intact (or that's ...
bool hasSameFunctionTypeIgnoringParamABI(QualType T, QualType U) const
Determine if two function types are the same, ignoring parameter ABI annotations.
TypedefDecl * getInt128Decl() const
Retrieve the declaration for the 128-bit signed integer type.
unsigned getOpenMPDefaultSimdAlign(QualType T) const
Get default simd alignment of the specified complete type in bits.
QualType getObjCSuperType() const
Returns the C struct type for objc_super.
QualType getBlockDescriptorType() const
Gets the struct used to keep track of the descriptor for pointer to blocks.
bool CommentsLoaded
True if comments are already loaded from ExternalASTSource.
BlockVarCopyInit getBlockVarCopyInit(const VarDecl *VD) const
Get the copy initialization expression of the VarDecl VD, or nullptr if none exists.
QualType getHLSLInlineSpirvType(uint32_t Opcode, uint32_t Size, uint32_t Alignment, ArrayRef< SpirvOperand > Operands)
unsigned NumImplicitMoveConstructorsDeclared
The number of implicitly-declared move constructors for which declarations were built.
bool isInSameModule(const Module *M1, const Module *M2) const
If the two module M1 and M2 are in the same module.
unsigned NumImplicitCopyConstructorsDeclared
The number of implicitly-declared copy constructors for which declarations were built.
QualType getLeastIntTypeForBitwidth(unsigned DestWidth, unsigned Signed) const
CanQualType IntTy
CanQualType PseudoObjectTy
QualType getWebAssemblyExternrefType() const
Return a WebAssembly externref type.
void setTraversalScope(const std::vector< Decl * > &)
CharUnits getTypeUnadjustedAlignInChars(QualType T) const
getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a type, in characters,...
QualType getAdjustedType(QualType Orig, QualType New) const
Return the uniqued reference to a type adjusted from the original type to a new type.
friend class NestedNameSpecifier
Definition ASTContext.h:246
void PrintStats() const
MangleContext * cudaNVInitDeviceMC()
unsigned getAlignOfGlobalVar(QualType T, const VarDecl *VD) const
Return the alignment in bits that should be given to a global variable with type T.
bool areCompatibleOverflowBehaviorTypes(QualType LHS, QualType RHS)
Return true if two OverflowBehaviorTypes are compatible for assignment.
TypeInfoChars getTypeInfoDataSizeInChars(QualType T) const
MangleNumberingContext & getManglingNumberContext(const DeclContext *DC)
Retrieve the context for computing mangling numbers in the given DeclContext.
comments::FullComment * getLocalCommentForDeclUncached(const Decl *D) const
Return parsed documentation comment attached to a given declaration.
unsigned NumImplicitDestructors
The number of implicitly-declared destructors.
CanQualType Float16Ty
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
bool isAlignmentRequired(const Type *T) const
Determine if the alignment the type has was required using an alignment attribute.
TagDecl * MSGuidTagDecl
bool areComparableObjCPointerTypes(QualType LHS, QualType RHS)
MangleContext * createDeviceMangleContext(const TargetInfo &T)
Creates a device mangle context to correctly mangle lambdas in a mixed architecture compile by settin...
CharUnits getExnObjectAlignment() const
Return the alignment (in bytes) of the thrown exception object.
CanQualType SignedCharTy
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
ASTMutationListener * Listener
Definition ASTContext.h:861
CanQualType ObjCBuiltinBoolTy
TypeInfoChars getTypeInfoInChars(const Type *T) const
QualType getPredefinedSugarType(PredefinedSugarType::Kind KD) const
QualType getObjCObjectType(QualType Base, ObjCProtocolDecl *const *Protocols, unsigned NumProtocols) const
Legacy interface: cannot provide type arguments or __kindof.
TemplateParamObjectDecl * getTemplateParamObjectDecl(QualType T, const APValue &V) const
Return the template parameter object of the given type with the given value.
interp::Context & getInterpContext() const
Returns the clang bytecode interpreter context.
CanQualType OverloadTy
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
int64_t toBits(CharUnits CharSize) const
Convert a size in characters to a size in bits.
TemplateTemplateParmDecl * getCanonicalTemplateTemplateParmDecl(TemplateTemplateParmDecl *TTP) const
Canonicalize the given TemplateTemplateParmDecl.
CanQualType OCLClkEventTy
void adjustExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI, bool AsWritten=false)
Change the exception specification on a function once it is delay-parsed, instantiated,...
TypedefDecl * getUInt128Decl() const
Retrieve the declaration for the 128-bit unsigned integer type.
bool hasPFPFields(QualType Ty) const
const clang::PrintingPolicy & getPrintingPolicy() const
Definition ASTContext.h:908
void ResetObjCLayout(const ObjCInterfaceDecl *D)
ArrayRef< Module * > getModulesWithMergedDefinition(const NamedDecl *Def)
Get the additional modules in which the definition Def has been merged.
void setCtorClosureDefaultArgs(const CXXConstructorDecl *CD, ArrayRef< CXXDefaultArgExpr * > Args)
llvm::FixedPointSemantics getFixedPointSemantics(QualType Ty) const
CanQualType SatUnsignedShortAccumTy
QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false, bool BlockReturnType=false, bool IsConditionalOperator=false)
CharUnits getAlignOfGlobalVarInChars(QualType T, const VarDecl *VD) const
Return the alignment in characters that should be given to a global variable with type T.
const ObjCMethodDecl * getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const
Get the duplicate declaration of a ObjCMethod in the same interface, or null if none exists.
QualType getPackIndexingType(QualType Pattern, Expr *IndexExpr, bool FullySubstituted=false, ArrayRef< QualType > Expansions={}, UnsignedOrNone Index=std::nullopt) const
static bool isObjCNSObjectType(QualType Ty)
Return true if this is an NSObject object with its NSObject attribute set.
GVALinkage GetGVALinkageForVariable(const VarDecl *VD) const
llvm::PointerUnion< VarTemplateDecl *, MemberSpecializationInfo * > TemplateOrSpecializationInfo
A type synonym for the TemplateOrInstantiation mapping.
Definition ASTContext.h:607
UsingShadowDecl * getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst)
QualType getVariableArrayType(QualType EltTy, Expr *NumElts, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return a non-unique reference to the type for a variable array of the specified element type.
QualType getObjCIdType() const
Represents the Objective-CC id type.
Decl * getVaListTagDecl() const
Retrieve the C type declaration corresponding to the predefined __va_list_tag type used to help defin...
QualType getUnsignedWCharType() const
Return the type of "unsigned wchar_t".
QualType getFunctionTypeWithoutParamABIs(QualType T) const
Get or construct a function type that is equivalent to the input type except that the parameter ABI a...
QualType getCorrespondingUnsaturatedType(QualType Ty) const
comments::FullComment * getCommentForDecl(const Decl *D, const Preprocessor *PP) const
Return parsed documentation comment attached to a given declaration.
TemplateArgument getInjectedTemplateArg(NamedDecl *ParamDecl) const
unsigned getTargetDefaultAlignForAttributeAligned() const
Return the default alignment for attribute((aligned)) on this target, to be used if no alignment valu...
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
llvm::DenseMap< CanQualType, SYCLKernelInfo > SYCLKernels
Map of SYCL kernels indexed by the unique type used to name the kernel.
bool isSameTemplateParameterList(const TemplateParameterList *X, const TemplateParameterList *Y) const
Determine whether two template parameter lists are similar enough that they may be used in declaratio...
QualType getWritePipeType(QualType T) const
Return a write_only pipe type for the specified type.
QualType getTypeDeclType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TypeDecl *Decl) const
bool isDestroyingOperatorDelete(const FunctionDecl *FD) const
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CanQualType UnsignedInt128Ty
CanQualType BuiltinFnTy
ObjCInterfaceDecl * getObjCProtocolDecl() const
Retrieve the Objective-C class declaration corresponding to the predefined Protocol class.
unsigned NumImplicitDefaultConstructors
The number of implicitly-declared default constructors.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
llvm::iterator_range< overridden_cxx_method_iterator > overridden_method_range
unsigned NumImplicitMoveAssignmentOperatorsDeclared
The number of implicitly-declared move assignment operators for which declarations were built.
void setManglingNumber(const NamedDecl *ND, unsigned Number)
CanQualType OCLSamplerTy
TypedefDecl * getBuiltinVaListDecl() const
Retrieve the C type declaration corresponding to the predefined __builtin_va_list type.
CanQualType getCanonicalTypeDeclType(const TypeDecl *TD) const
CanQualType VoidTy
QualType getPackExpansionType(QualType Pattern, UnsignedOrNone NumExpansions, bool ExpectPackInType=true) const
Form a pack expansion type with the given pattern.
CanQualType UnsignedCharTy
CanQualType UnsignedShortFractTy
BuiltinTemplateDecl * buildBuiltinTemplateDecl(BuiltinTemplateKind BTK, const IdentifierInfo *II) const
void * Allocate(size_t Size, unsigned Align=8) const
Definition ASTContext.h:929
ArrayRef< ExplicitInstantiationDecl * > getExplicitInstantiationDecls(const NamedDecl *Spec) const
Get all ExplicitInstantiationDecls for a given specialization.
bool canBuiltinBeRedeclared(const FunctionDecl *) const
Return whether a declaration to a builtin is allowed to be overloaded/redeclared.
CanQualType UnsignedIntTy
unsigned NumImplicitMoveConstructors
The number of implicitly-declared move constructors.
QualType getTypedefType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TypedefNameDecl *Decl, QualType UnderlyingType=QualType(), std::optional< bool > TypeMatchesDeclOrNone=std::nullopt) const
Return the unique reference to the type for the specified typedef-name decl.
QualType getObjCTypeParamType(const ObjCTypeParamDecl *Decl, ArrayRef< ObjCProtocolDecl * > protocols) const
void getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT, QualType T, std::string &S, bool Extended) const
getObjCEncodingForMethodParameter - Return the encoded type for a single method parameter or return t...
static bool isPFPField(const FieldDecl *Field)
void addDeclaratorForUnnamedTagDecl(TagDecl *TD, DeclaratorDecl *DD)
unsigned overridden_methods_size(const CXXMethodDecl *Method) const
std::string getObjCEncodingForBlock(const BlockExpr *blockExpr) const
Return the encoded type for this block declaration.
QualType getTemplateSpecializationType(ElaboratedTypeKeyword Keyword, TemplateName T, ArrayRef< TemplateArgument > SpecifiedArgs, ArrayRef< TemplateArgument > CanonicalArgs, QualType Underlying=QualType()) const
TypeSourceInfo * CreateTypeSourceInfo(QualType T, unsigned Size=0) const
Allocate an uninitialized TypeSourceInfo.
TemplateName getQualifiedTemplateName(NestedNameSpecifier Qualifier, bool TemplateKeyword, TemplateName Template) const
Retrieve the template name that represents a qualified template name such as std::vector.
bool isSameAssociatedConstraint(const AssociatedConstraint &ACX, const AssociatedConstraint &ACY) const
Determine whether two 'requires' expressions are similar enough that they may be used in re-declarati...
QualType getExceptionObjectType(QualType T) const
CanQualType UnknownAnyTy
void setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl, TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation=SourceLocation())
Note that the static data member Inst is an instantiation of the static data member template Tmpl of ...
FieldDecl * getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) const
DeclaratorDecl * getDeclaratorForUnnamedTagDecl(const TagDecl *TD)
bool ObjCObjectAdoptsQTypeProtocols(QualType QT, ObjCInterfaceDecl *Decl)
ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's protocol list adopt all protocols in Q...
CanQualType UnsignedLongLongTy
QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error, unsigned *IntegerConstantArgs=nullptr) const
Return the type for the specified builtin.
CanQualType OCLReserveIDTy
bool isSameTemplateParameter(const NamedDecl *X, const NamedDecl *Y) const
Determine whether two template parameters are similar enough that they may be used in declarations of...
void registerSYCLEntryPointFunction(FunctionDecl *FD)
Generates and stores SYCL kernel metadata for the provided SYCL kernel entry point function.
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
overridden_cxx_method_iterator overridden_methods_begin(const CXXMethodDecl *Method) const
CanQualType UnsignedShortTy
FunctionDecl * getOperatorDeleteForVDtor(const CXXDestructorDecl *Dtor, OperatorDeleteKind K) const
AttrVec * allocateAttrVec()
Allocate an empty attribute vector with the lifetime of this context.
unsigned getTypeAlignIfKnown(QualType T, bool NeedsPreferredAlignment=false) const
Return the alignment of a type, in bits, or 0 if the type is incomplete and we cannot determine the a...
void UnwrapSimilarArrayTypes(QualType &T1, QualType &T2, bool AllowPiMismatch=true) const
Attempt to unwrap two types that may both be array types with the same bound (or both be array types ...
bool isRepresentableIntegerValue(llvm::APSInt &Value, QualType T)
Determine whether the given integral value is representable within the given type T.
bool AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
llvm::DenseMap< RawCommentLookupKey, const RawComment * > RawComments
Mapping from declaration or macro to directly attached comment.
const SYCLKernelInfo & getSYCLKernelInfo(QualType T) const
Given a type used as a SYCL kernel name, returns a reference to the metadata generated from the corre...
bool canAssignObjCInterfacesInBlockPointer(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT, bool BlockReturnType)
canAssignObjCInterfacesInBlockPointer - This routine is specifically written for providing type-safet...
CanQualType SatUnsignedLongFractTy
QualType getMemberPointerType(QualType T, NestedNameSpecifier Qualifier, const CXXRecordDecl *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
static bool hasSameType(QualType T1, QualType T2)
Determine whether the given types T1 and T2 are equivalent.
const CXXConstructorDecl * getCopyConstructorForExceptionObject(CXXRecordDecl *RD)
QualType getDependentAddressSpaceType(QualType PointeeType, Expr *AddrSpaceExpr, SourceLocation AttrLoc) const
QualType getTagType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TagDecl *TD, bool OwnsTag) const
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
CanQualType getMSGuidType() const
Retrieve the implicitly-predeclared 'struct _GUID' type.
const VariableArrayType * getAsVariableArrayType(QualType T) const
QualType getUnaryTransformType(QualType BaseType, QualType UnderlyingType, UnaryTransformType::UTTKind UKind) const
Unary type transforms.
void setExternalSource(IntrusiveRefCntPtr< ExternalASTSource > Source)
Attach an external AST source to the AST context.
const ObjCInterfaceDecl * getObjContainingInterface(const NamedDecl *ND) const
Returns the Objective-C interface that ND belongs to if it is an Objective-C method/property/ivar etc...
CanQualType ShortTy
StringLiteral * getPredefinedStringLiteralFromCache(StringRef Key) const
Return a string representing the human readable name for the specified function declaration or file n...
CanQualType getCanonicalUnresolvedUsingType(const UnresolvedUsingTypenameDecl *D) const
bool hasSimilarType(QualType T1, QualType T2) const
Determine if two types are similar, according to the C++ rules.
llvm::APFixedPoint getFixedPointMax(QualType Ty) const
QualType getComplexType(QualType T) const
Return the uniqued reference to the type for a complex number with the specified element type.
bool classMaybeNeedsVectorDeletingDestructor(const CXXRecordDecl *RD)
QualType getTemplateTypeParmType(int Depth, int Index, bool ParameterPack, TemplateTypeParmDecl *ParmDecl=nullptr) const
Retrieve the template type parameter type for a template parameter or parameter pack with the given d...
bool hasDirectOwnershipQualifier(QualType Ty) const
Return true if the type has been explicitly qualified with ObjC ownership.
CanQualType FractTy
Qualifiers::ObjCLifetime getInnerObjCOwnership(QualType T) const
Recurses in pointer/array types until it finds an Objective-C retainable type and returns its ownersh...
void addCopyConstructorForExceptionObject(CXXRecordDecl *RD, CXXConstructorDecl *CD)
void deduplicateMergedDefinitionsFor(NamedDecl *ND)
Clean up the merged definition list.
static uint64_t getConstantArrayElementCount(const ConstantArrayType *CA)
Return number of (potentially nested) constant array elements.
DiagnosticsEngine & getDiagnostics() const
QualType getAdjustedParameterType(QualType T) const
Perform adjustment on the parameter type of a function.
CanQualType LongAccumTy
CanQualType Char32Ty
void recordOffsetOfEvaluation(const OffsetOfExpr *E)
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
UnnamedGlobalConstantDecl * getUnnamedGlobalConstantDecl(QualType Ty, const APValue &Value) const
Return a declaration for a uniquified anonymous global constant corresponding to a given APValue.
CanQualType SatFractTy
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size.
QualType getUnresolvedUsingType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const UnresolvedUsingTypenameDecl *D) const
bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec)
Return true if the given vector types are of the same unqualified type or if they are equivalent to t...
void getOverriddenMethods(const NamedDecl *Method, SmallVectorImpl< const NamedDecl * > &Overridden) const
Return C++ or ObjC overridden methods for the given Method.
DeclarationNameInfo getNameForTemplate(TemplateName Name, SourceLocation NameLoc) const
bool hasSameTemplateName(const TemplateName &X, const TemplateName &Y, bool IgnoreDeduced=false) const
Determine whether the given template names refer to the same template.
CanQualType SatLongFractTy
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:974
void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl)
CanQualType OCLQueueTy
CanQualType LongFractTy
OBTAssignResult checkOBTAssignmentCompatibility(QualType LHS, QualType RHS)
Check overflow behavior type compatibility for assignments.
CanQualType SatShortAccumTy
QualType getAutoDeductType() const
C++11 deduction pattern for 'auto' type.
CanQualType BFloat16Ty
unsigned NumImplicitCopyConstructors
The number of implicitly-declared copy constructors.
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
static uint64_t getArrayInitLoopExprElementCount(const ArrayInitLoopExpr *AILE)
Return number of elements initialized in a (potentially nested) ArrayInitLoopExpr.
void addExplicitInstantiationDecl(const NamedDecl *Spec, ExplicitInstantiationDecl *EID)
Add an ExplicitInstantiationDecl for a given specialization.
QualType getOverflowBehaviorType(const OverflowBehaviorAttr *Attr, QualType Wrapped) const
CanQualType IncompleteMatrixIdxTy
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
bool shouldEmitCUDADecl(const ValueDecl *D) const
Determines if the global variable or function D is emitted on the side of the CUDA/HIP compilation,...
TargetCXXABI::Kind getCXXABIKind() const
Return the C++ ABI kind that should be used.
QualType getHLSLAttributedResourceType(QualType Wrapped, QualType Contained, const HLSLAttributedResourceType::Attributes &Attrs)
bool UnwrapSimilarTypes(QualType &T1, QualType &T2, bool AllowPiMismatch=true) const
Attempt to unwrap two types that may be similar (C++ [conv.qual]).
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
QualType getSignedSizeType() const
Return the unique signed counterpart of the integer type corresponding to size_t.
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any.
CanQualType SatUnsignedLongAccumTy
QualType getUnconstrainedType(QualType T) const
Remove any type constraints from a template parameter type, for equivalence comparison of template pa...
CanQualType LongLongTy
CanQualType getCanonicalTagType(const TagDecl *TD) const
bool isSameTemplateArgument(const TemplateArgument &Arg1, const TemplateArgument &Arg2) const
Determine whether the given template arguments Arg1 and Arg2 are equivalent.
QualType getTypeOfType(QualType QT, TypeOfKind Kind) const
getTypeOfType - Unlike many "get<Type>" functions, we don't unique TypeOfType nodes.
QualType getCorrespondingSignedType(QualType T) const
QualType mergeObjCGCQualifiers(QualType, QualType)
mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and 'RHS' attributes and ret...
llvm::DenseMap< const Decl *, const Decl * > CommentlessRedeclChains
Keeps track of redeclaration chains that don't have any comment attached.
unsigned getTargetAddressSpace(LangAS AS) const
ParentMapContext & getParentMapContext()
Returns the dynamic AST node parent map context.
Definition ASTContext.h:881
std::vector< PFPField > findPFPFields(QualType Ty) const
Returns a list of PFP fields for the given type, including subfields in bases or other fields,...
QualType getIntPtrType() const
Return a type compatible with "intptr_t" (C99 7.18.1.4), as defined by the target.
void mergeDefinitionIntoModule(NamedDecl *ND, Module *M, bool NotifyListeners=true)
Note that the definition ND has been merged into module M, and should be visible whenever M is visibl...
QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return a non-unique reference to the type for a dependently-sized array of the specified element type...
void addTranslationUnitDecl()
CanQualType WCharTy
void getObjCEncodingForPropertyType(QualType T, std::string &S) const
Emit the Objective-C property type encoding for the given type T into S.
unsigned NumImplicitCopyAssignmentOperators
The number of implicitly-declared copy assignment operators.
void CollectInheritedProtocols(const Decl *CDecl, llvm::SmallPtrSet< ObjCProtocolDecl *, 8 > &Protocols)
CollectInheritedProtocols - Collect all protocols in current class and those inherited by it.
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
llvm::DenseMap< const Decl *, const Decl * > RedeclChainComments
Mapping from canonical declaration to the first redeclaration in chain that has a comment attached.
void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType)
Change the result type of a function type once it is deduced.
QualType getObjCGCQualType(QualType T, Qualifiers::GC gcAttr) const
Return the uniqued reference to the type for an Objective-C gc-qualified type.
QualType getDecltypeType(Expr *e, QualType UnderlyingType) const
C++11 decltype.
std::optional< CXXRecordDeclRelocationInfo > getRelocationInfoForCXXRecord(const CXXRecordDecl *) const
static bool hasSameUnqualifiedType(QualType T1, QualType T2)
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
InlineVariableDefinitionKind getInlineVariableDefinitionKind(const VarDecl *VD) const
Determine whether a definition of this inline variable should be treated as a weak or strong definiti...
const RawComment * getRawCommentForAnyRedecl(RawCommentLookupKey Key, const Decl **OriginalDecl=nullptr) const
Return the documentation comment attached to a given declaration or macro.
TemplateName getSubstTemplateTemplateParm(TemplateName replacement, Decl *AssociatedDecl, unsigned Index, UnsignedOrNone PackIndex, bool Final) const
CanQualType getUIntMaxType() const
Return the unique type for "uintmax_t" (C99 7.18.1.5), defined in <stdint.h>.
friend class DeclContext
CharUnits getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const
Loading virtual member pointers using the virtual inheritance model always results in an adjustment u...
LangAS getLangASForBuiltinAddressSpace(unsigned AS) const
bool hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U)
Determine whether two function types are the same, ignoring pointer sizes in the return type and para...
void addOperatorDeleteForVDtor(const CXXDestructorDecl *Dtor, FunctionDecl *OperatorDelete, OperatorDeleteKind K) const
unsigned char getFixedPointScale(QualType Ty) const
QualType getIncompleteArrayType(QualType EltTy, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return a unique reference to the type for an incomplete array of the specified element type.
QualType getDependentSizedExtVectorType(QualType VectorType, Expr *SizeExpr, SourceLocation AttrLoc) const
QualType DecodeTypeStr(const char *&Str, const ASTContext &Context, ASTContext::GetBuiltinTypeError &Error, bool &RequireICE, bool AllowTypeModifiers) const
TemplateName getAssumedTemplateName(DeclarationName Name) const
Retrieve a template name representing an unqualified-id that has been assumed to name a template for ...
@ GE_None
No error.
@ GE_Missing_type
Missing a type.
QualType adjustStringLiteralBaseType(QualType StrLTy) const
uint16_t getPointerAuthTypeDiscriminator(QualType T)
Return the "other" type-specific discriminator for the given type.
llvm::SetVector< const FieldDecl * > PFPFieldsWithEvaluatedOffset
uint16_t getPointerAuthVTablePointerDiscriminator(const CXXRecordDecl *RD, bool IsVTTEntry)
Return the "other" discriminator used for the pointer auth schema used for vtable pointers using the ...
bool canonicalizeTemplateArguments(MutableArrayRef< TemplateArgument > Args) const
Canonicalize the given template argument list.
QualType getTypeOfExprType(Expr *E, TypeOfKind Kind) const
C23 feature and GCC extension.
QualType getMatrixTypeWithLayout(QualType T, MatrixType::LayoutKind Layout) const
CanQualType Char8Ty
bool isUnaryOverflowPatternExcluded(const UnaryOperator *UO)
QualType getSignedWCharType() const
Return the type of "signed wchar_t".
QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals) const
Return this type as a completely-unqualified array type, capturing the qualifiers in Quals.
bool hasCvrSimilarType(QualType T1, QualType T2)
Determine if two types are similar, ignoring only CVR qualifiers.
TemplateName getDeducedTemplateName(TemplateName Underlying, DefaultArguments DefaultArgs) const
Represents a TemplateName which had some of its default arguments deduced.
ObjCImplementationDecl * getObjCImplementation(ObjCInterfaceDecl *D)
Get the implementation of the ObjCInterfaceDecl D, or nullptr if none exists.
CanQualType HalfTy
CanQualType UnsignedAccumTy
void setObjCMethodRedeclaration(const ObjCMethodDecl *MD, const ObjCMethodDecl *Redecl)
void addTypedefNameForUnnamedTagDecl(TagDecl *TD, TypedefNameDecl *TND)
const CXXRecordDecl * baseForVTableAuthentication(const CXXRecordDecl *ThisClass) const
Resolve the root record to be used to derive the vtable pointer authentication policy for the specifi...
void cacheRawComment(RawCommentLookupKey Original, const RawComment &Comment) const
Attaches Comment to Original (a declaration or macro), and to its redeclaration chain when Original i...
QualType getVariableArrayDecayedType(QualType Ty) const
Returns a vla type where known sizes are replaced with [*].
void setCFConstantStringType(QualType T)
const SYCLKernelInfo * findSYCLKernelInfo(QualType T) const
Returns a pointer to the metadata generated from the corresponding SYCLkernel entry point if the prov...
unsigned getParameterIndex(const ParmVarDecl *D) const
Used by ParmVarDecl to retrieve on the side the index of the parameter when it exceeds the size of th...
QualType getCommonSugaredType(QualType X, QualType Y, bool Unqualified=false) const
CanQualType OCLEventTy
void AddDeallocation(void(*Callback)(void *), void *Data) const
Add a deallocation callback that will be invoked when the ASTContext is destroyed.
QualType getDeducedTemplateSpecializationType(DeducedKind DK, QualType DeducedAsType, ElaboratedTypeKeyword Keyword, TemplateName Template) const
C++17 deduced class template specialization type.
CXXMethodVector::const_iterator overridden_cxx_method_iterator
unsigned getTypeAlign(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in bits.
QualType mergeTransparentUnionType(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false)
mergeTransparentUnionType - if T is a transparent union type and a member of T is compatible with Sub...
QualType isPromotableBitField(Expr *E) const
Whether this is a promotable bitfield reference according to C99 6.3.1.1p2, bullet 2 (and GCC extensi...
bool isSentinelNullExpr(const Expr *E)
CanQualType getNSUIntegerType() const
void setIsDestroyingOperatorDelete(const FunctionDecl *FD, bool IsDestroying)
TypedefDecl * getBuiltinZOSVaListDecl() const
Retrieve the C type declaration corresponding to the predefined __builtin_zos_va_list type.
void recordMemberDataPointerEvaluation(const ValueDecl *VD)
uint64_t getCharWidth() const
Return the size of the character type, in bits.
QualType getBitIntType(bool Unsigned, unsigned NumBits) const
Return a bit-precise integer type with the specified signedness and bit count.
unsigned NumImplicitMoveAssignmentOperators
The number of implicitly-declared move assignment operators.
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
virtual void DeducedReturnType(const FunctionDecl *FD, QualType ReturnType)
A function's return type has been deduced.
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
bool hasOwnVFPtr() const
hasOwnVFPtr - Does this class provide its own virtual-function table pointer, rather than inheriting ...
CharUnits getAlignment() const
getAlignment - Get the record alignment in characters.
const CXXRecordDecl * getBaseSharingVBPtr() const
bool hasOwnVBPtr() const
hasOwnVBPtr - Does this class provide its own virtual-base table pointer, rather than inheriting one ...
CharUnits getSize() const
getSize - Get the record size in characters.
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
CharUnits getVBPtrOffset() const
getVBPtrOffset - Get the offset for virtual base table pointer.
CharUnits getDataSize() const
getDataSize() - Get the record data size, which is the record size without tail padding,...
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
CharUnits getVBaseClassOffset(const CXXRecordDecl *VBase) const
getVBaseClassOffset - Get the offset, in chars, for the given base class.
CharUnits getNonVirtualSize() const
getNonVirtualSize - Get the non-virtual size (in chars) of an object, which is the size of the object...
CharUnits getUnadjustedAlignment() const
getUnadjustedAlignment - Get the record alignment in characters, before alignment adjustment.
Represents a type which was implicitly adjusted by the semantic engine for arbitrary reasons.
Definition TypeBase.h:3605
Represents a loop initializing the elements of an array.
Definition Expr.h:6054
llvm::APInt getArraySize() const
Definition Expr.h:6076
Expr * getSubExpr() const
Get the initializer to use for each array element.
Definition Expr.h:6074
Represents a constant array type that does not decay to a pointer when used as a function parameter.
Definition TypeBase.h:3990
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3820
ArraySizeModifier getSizeModifier() const
Definition TypeBase.h:3834
Qualifiers getIndexTypeQualifiers() const
Definition TypeBase.h:3838
QualType getElementType() const
Definition TypeBase.h:3832
unsigned getIndexTypeCVRQualifiers() const
Definition TypeBase.h:3842
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:7014
Expr * getPtr() const
Definition Expr.h:7045
Attr - This represents one attribute.
Definition Attr.h:47
attr::Kind getKind() const
Definition Attr.h:93
A fixed int type of a specified bitwidth.
Definition TypeBase.h:8436
unsigned getNumBits() const
Definition TypeBase.h:8448
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition Decl.h:4856
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition Expr.h:6758
Pointer to a block type.
Definition TypeBase.h:3653
Represents the builtin template declaration which is used to implement __make_integer_seq and other b...
static BuiltinTemplateDecl * Create(const ASTContext &C, DeclContext *DC, DeclarationName Name, BuiltinTemplateKind BTK)
This class is used for builtin types like 'int'.
Definition TypeBase.h:3245
Kind getKind() const
Definition TypeBase.h:3299
Holds information about both target-independent and target-specific builtins, allowing easy queries b...
Definition Builtins.h:238
Implements C++ ABI-specific semantic analysis functions.
Definition CXXABI.h:29
virtual ~CXXABI()
Represents a base class of a C++ class.
Definition DeclCXX.h:146
Represents a C++ constructor within a class.
Definition DeclCXX.h:2645
Represents a C++ destructor within a class.
Definition DeclCXX.h:2924
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2153
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2266
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr)
Definition DeclCXX.cpp:133
CXXRecordDecl * getDefinition() const
Definition DeclCXX.h:549
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition DeclCXX.h:1224
bool isDynamicClass() const
Definition DeclCXX.h:575
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition DeclCXX.h:1196
SplitQualType split() const
static CanQual< Type > CreateUnsafe(QualType Other)
QualType withConst() const
Retrieves a version of this type with const applied.
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
Qualifiers getQualifiers() const
Retrieve all qualifiers.
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
bool isPositive() const
Test whether the quantity is greater than zero.
Definition CharUnits.h:107
bool isZero() const
Test whether the quantity equals zero.
Definition CharUnits.h:101
CharUnits alignTo(CharUnits Align) const
Returns the next integer (mod 2**64) that is greater than or equal to this quantity and is a multiple...
Definition CharUnits.h:171
QuantityType getQuantity() const
Get the raw integer representation of this quantity.
Definition CharUnits.h:155
static constexpr CharUnits fromQuantity(QuantityType Quantity)
Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:58
static CharUnits Zero()
Construct a CharUnits quantity of zero.
Definition CharUnits.h:52
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3362
QualType getElementType() const
Definition TypeBase.h:3372
bool hasExplicitTemplateArgs() const
Whether or not template arguments were explicitly specified in the concept reference (they might not ...
Definition ASTConcept.h:206
const ASTTemplateArgumentListInfo * getTemplateArgsAsWritten() const
Definition ASTConcept.h:200
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3858
const Expr * getSizeExpr() const
Return a pointer to the size expression.
Definition TypeBase.h:3954
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3914
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition TypeBase.h:3973
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3934
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4622
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition TypeBase.h:4644
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:4692
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition TypeBase.h:4641
Represents a sugar type with __counted_by or __sized_by annotations, including their _or_null variant...
Definition TypeBase.h:3509
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3554
Represents a pointer type decayed from an array or function type.
Definition TypeBase.h:3636
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1467
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2110
bool isFileContext() const
Definition DeclBase.h:2201
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition DeclBase.h:2126
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
void addDecl(Decl *D)
Add the declaration D into this context.
DeclContext * getPrimaryContext()
getPrimaryContext - There may be many different declarations of the same entity (including forward de...
Decl::Kind getDeclKind() const
Definition DeclBase.h:2103
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1315
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
const DeclContext * getParentFunctionOrMethod(bool LexicalParent=false) const
If this decl is defined inside a function/method/block it returns the corresponding DeclContext,...
Definition DeclBase.cpp:344
bool isModuleLocal() const
Whether this declaration was a local declaration to a C++20 named module.
T * getAttr() const
Definition DeclBase.h:582
bool hasAttrs() const
Definition DeclBase.h:527
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:550
void addAttr(Attr *A)
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:602
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl,...
Definition DeclBase.cpp:572
bool isUnconditionallyVisible() const
Determine whether this declaration is definitely visible to name lookup, independent of whether the o...
Definition DeclBase.h:872
static Decl * castFromDeclContext(const DeclContext *)
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition DeclBase.cpp:308
bool isCanonicalDecl() const
Whether this particular Decl is a canonical one.
Definition DeclBase.h:1002
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition DeclBase.h:855
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition DeclBase.cpp:273
ObjCDeclQualifier
ObjCDeclQualifier - 'Qualifiers' written next to the return and parameter types in method declaration...
Definition DeclBase.h:198
bool isInvalidDecl() const
Definition DeclBase.h:597
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:568
void setImplicit(bool I=true)
Definition DeclBase.h:603
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition DeclBase.h:1067
DeclContext * getDeclContext()
Definition DeclBase.h:457
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition DeclBase.cpp:385
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:936
bool hasAttr() const
Definition DeclBase.h:586
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:996
Kind getKind() const
Definition DeclBase.h:451
DeclarationNameLoc - Additional source/type location info for a declaration name.
static DeclarationNameLoc makeCXXOperatorNameLoc(SourceLocation BeginLoc, SourceLocation EndLoc)
Construct location information for a non-literal C++ operator.
The name of a declaration.
static int compare(DeclarationName LHS, DeclarationName RHS)
Represents a ValueDecl that came out of a declarator.
Definition Decl.h:782
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:811
TemplateName getUnderlying() const
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) const
DefaultArguments getDefaultArguments() const
Represents an extended address space qualifier where the input address space value is dependent.
Definition TypeBase.h:4159
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4181
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:8475
Represents an array type in C++ whose size is a value-dependent expression.
Definition TypeBase.h:4109
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4138
Represents an extended vector type where either the type or size is dependent.
Definition TypeBase.h:4199
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4224
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition TypeBase.h:4714
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4734
Represents a dependent template name that cannot be resolved prior to template instantiation.
void Profile(llvm::FoldingSetNodeID &ID) const
IdentifierOrOverloadedOperator getName() const
NestedNameSpecifier getQualifier() const
Return the nested name specifier that qualifies this name.
bool hasTemplateKeyword() const
Was this template name was preceeded by the template keyword?
Internal representation of canonical, dependent typeof(expr) types.
Definition TypeBase.h:6492
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:6497
Represents a vector type where either the type or size is dependent.
Definition TypeBase.h:4457
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4482
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:240
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
A dynamically typed AST node container.
Represents an enum.
Definition Decl.h:4192
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition Decl.h:4410
bool isComplete() const
Returns true if this can be considered a complete type.
Definition Decl.h:4424
EnumDecl * getDefinitionOrSelf() const
Definition Decl.h:4308
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4365
Represents an explicit instantiation of a template entity in source code.
This represents one expression.
Definition Expr.h:114
bool isIntegerConstantExpr(const ASTContext &Ctx) const
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3134
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:179
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:449
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:196
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition Expr.cpp:4271
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:876
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on.
Definition Expr.h:225
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, bool AllowRelaxedEval=false) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3109
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:4110
QualType getType() const
Definition Expr.h:146
We can encode up to four bits in the low bits of a type pointer, but there are many more type qualifi...
Definition TypeBase.h:1736
void Profile(llvm::FoldingSetNodeID &ID) const
Definition TypeBase.h:1783
ExtVectorType - Extended vector type.
Definition TypeBase.h:4497
Declaration context for names declared as extern "C" in C++.
Definition Decl.h:249
static ExternCContextDecl * Create(const ASTContext &C, TranslationUnitDecl *TU)
Definition Decl.cpp:5658
Abstract interface for external sources of AST nodes.
Represents a member of a struct/union/class.
Definition Decl.h:3341
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3444
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition Decl.cpp:4857
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition Decl.h:3426
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3577
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:4805
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
bool isValid() const
Represents a function declaration or definition.
Definition Decl.h:2082
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition Decl.h:2862
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3838
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition Decl.h:3098
bool isMSExternInline() const
The combination of the extern and inline keywords under MSVC forces the function to be required.
Definition Decl.cpp:3972
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3823
FunctionDecl * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
FunctionDecl * getDefinition()
Get the definition for this declaration.
Definition Decl.h:2438
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition Decl.cpp:4495
bool isUserProvided() const
True if this method is user-declared and was not deleted or defaulted on its first declaration.
Definition Decl.h:2579
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:4156
FunctionDecl * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
SmallVector< Conflict > Conflicts
Definition TypeBase.h:5516
static FunctionEffectSet getIntersection(FunctionEffectsRef LHS, FunctionEffectsRef RHS)
Definition Type.cpp:6062
static FunctionEffectSet getUnion(FunctionEffectsRef LHS, FunctionEffectsRef RHS, Conflicts &Errs)
Definition Type.cpp:6100
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5348
ArrayRef< EffectConditionExpr > conditions() const
Definition TypeBase.h:5382
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition TypeBase.h:5126
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:5142
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5548
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition TypeBase.h:6052
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition TypeBase.h:5855
unsigned getNumParams() const
Definition TypeBase.h:5826
QualType getParamType(unsigned i) const
Definition TypeBase.h:5828
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition Type.cpp:4244
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition TypeBase.h:5861
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5952
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5837
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5833
ArrayRef< ExtParameterInfo > getExtParameterInfos() const
Definition TypeBase.h:6021
bool hasExtParameterInfos() const
Is there any interesting extra information for any of the parameters of this function type?
Definition TypeBase.h:6017
Declaration of a template function.
A class which abstracts out some details necessary for making a call.
Definition TypeBase.h:4855
CallingConv getCC() const
Definition TypeBase.h:4914
unsigned getRegParm() const
Definition TypeBase.h:4907
bool getNoCallerSavedRegs() const
Definition TypeBase.h:4903
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4926
Interesting information about a specific parameter that can't simply be reflected in parameter's type...
Definition TypeBase.h:4770
ExtParameterInfo withIsNoEscape(bool NoEscape) const
Definition TypeBase.h:4810
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4744
ExtInfo getExtInfo() const
Definition TypeBase.h:5100
QualType getReturnType() const
Definition TypeBase.h:5084
GlobalDecl - represents a global declaration.
Definition GlobalDecl.h:60
unsigned getMultiVersionIndex() const
Definition GlobalDecl.h:134
CXXDtorType getDtorType() const
Definition GlobalDecl.h:122
const Decl * getDecl() const
Definition GlobalDecl.h:115
One of these records is kept for each identifier that is lexed.
unsigned getLength() const
Efficiently return the length of this identifier info.
StringRef getName() const
Return the actual identifier string.
Implements an efficient mapping from strings to IdentifierInfo nodes.
Describes a module import declaration, which makes the contents of the named module visible in the cu...
Definition Decl.h:5240
Represents a C array with an unspecified size.
Definition TypeBase.h:4007
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:4024
static ItaniumMangleContext * create(ASTContext &Context, DiagnosticsEngine &Diags, bool IsAux=false)
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3715
@ Swift
Interoperability with the latest known version of the Swift runtime.
@ Swift4_2
Interoperability with the Swift 4.2 runtime.
@ Swift4_1
Interoperability with the Swift 4.1 runtime.
@ Integer
Permit vector bitcasts between integer vectors with different numbers of elements but the same total ...
@ All
Permit vector bitcasts between all vectors with the same total bit-width.
@ PostDecrInWhile
while (count–)
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
std::optional< TargetCXXABI::Kind > CXXABI
C++ ABI to compile with, if specified by the frontend through -fc++-abi=.
clang::ObjCRuntime ObjCRuntime
CoreFoundationABI CFRuntime
bool isOverflowPatternExcluded(OverflowPatternExclusionKind Kind) const
Represents a placeholder type for late-parsed type attributes.
Definition TypeBase.h:3577
A global _GUID constant.
Definition DeclCXX.h:4468
static void Profile(llvm::FoldingSetNodeID &ID, Parts P)
Definition DeclCXX.h:4505
MSGuidDeclParts Parts
Definition DeclCXX.h:4470
Sugar type that represents a type that was qualified by a qualifier written as a macro invocation.
Definition TypeBase.h:6426
MangleContext - Context for tracking state which persists across multiple calls to the C++ name mangl...
Definition Mangle.h:56
Keeps track of the mangled names of lambda expressions and block literals within a particular context...
static bool isValidElementType(QualType T, const LangOptions &LangOpts)
Valid elements types are the following:
Definition TypeBase.h:4593
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition TypeBase.h:4586
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3751
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3794
Provides information a specialization of a member of a class template, which may be a member function...
static MicrosoftMangleContext * create(ASTContext &Context, DiagnosticsEngine &Diags, bool IsAux=false)
Describes a module or submodule.
Definition Module.h:340
bool isNamedModule() const
Does this Module is a named module of a standard named module?
Definition Module.h:426
This represents a decl that may have a name.
Definition Decl.h:276
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:489
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:297
bool isPlaceholderVar(const LangOptions &LangOpts) const
Definition Decl.cpp:1097
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:342
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:319
bool isExternallyVisible() const
Definition Decl.h:435
Represent a C++ namespace.
Definition Decl.h:594
static NamespaceDecl * Create(ASTContext &C, DeclContext *DC, bool Inline, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, NamespaceDecl *PrevDecl, bool Nested)
Definition DeclCXX.cpp:3374
A C++ nested-name-specifier augmented with source location information.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
NestedNameSpecifier getCanonical() const
Retrieves the "canonical" nested name specifier for a given nested name specifier.
CXXRecordDecl * getAsMicrosoftSuper() const
NamespaceAndPrefix getAsNamespaceAndPrefix() const
Kind
The kind of specifier that completes this nested name specifier.
@ MicrosoftSuper
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
@ Global
The global specifier '::'. There is no stored value.
@ Namespace
A namespace-like entity, stored as a NamespaceBaseDecl*.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
static NonTypeTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, int D, int P, const IdentifierInfo *Id, QualType T, bool ParameterPack, TypeSourceInfo *TInfo)
ObjCCategoryDecl - Represents a category declaration.
Definition DeclObjC.h:2335
ObjCCategoryImplDecl - An object of this class encapsulates a category @implementation declaration.
Definition DeclObjC.h:2551
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition DeclObjC.h:2603
Represents an ObjC class declaration.
Definition DeclObjC.h:1160
ObjCTypeParamList * getTypeParamList() const
Retrieve the type parameters of this class.
Definition DeclObjC.cpp:319
static ObjCInterfaceDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation atLoc, const IdentifierInfo *Id, ObjCTypeParamList *typeParamList, ObjCInterfaceDecl *PrevDecl, SourceLocation ClassLoc=SourceLocation(), bool isInternal=false)
bool hasDefinition() const
Determine whether this class has been defined.
Definition DeclObjC.h:1534
ivar_range ivars() const
Definition DeclObjC.h:1457
bool ClassImplementsProtocol(ObjCProtocolDecl *lProto, bool lookupCategory, bool RHSIsQualifiedID=false)
ClassImplementsProtocol - Checks that 'lProto' protocol has been implemented in IDecl class,...
StringRef getObjCRuntimeNameAsString() const
Produce a name to be used for class's metadata.
ObjCImplementationDecl * getImplementation() const
ObjCInterfaceDecl * getSuperClass() const
Definition DeclObjC.cpp:349
bool isSuperClassOf(const ObjCInterfaceDecl *I) const
isSuperClassOf - Return true if this class is the specified class or is a super class of the specifie...
Definition DeclObjC.h:1816
known_extensions_range known_extensions() const
Definition DeclObjC.h:1768
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition TypeBase.h:8163
ObjCInterfaceDecl * getDecl() const
Get the declaration of this interface.
Definition Type.cpp:1084
ObjCIvarDecl - Represents an ObjC instance variable.
Definition DeclObjC.h:1958
ObjCIvarDecl * getNextIvar()
Definition DeclObjC.h:1993
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:350
param_const_iterator param_end() const
Definition DeclObjC.h:361
param_const_iterator param_begin() const
Definition DeclObjC.h:357
bool isVariadic() const
Definition DeclObjC.h:434
const ParmVarDecl *const * param_const_iterator
Definition DeclObjC.h:352
Selector getSelector() const
Definition DeclObjC.h:330
bool isInstanceMethod() const
Definition DeclObjC.h:429
QualType getReturnType() const
Definition DeclObjC.h:332
Represents a pointer to an Objective C object.
Definition TypeBase.h:8219
bool isObjCQualifiedClassType() const
True if this is equivalent to 'Class.
Definition TypeBase.h:8300
const ObjCObjectPointerType * stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const
Strip off the Objective-C "kindof" type and (with it) any protocol qualifiers.
Definition Type.cpp:1091
bool isObjCQualifiedIdType() const
True if this is equivalent to 'id.
Definition TypeBase.h:8294
const ObjCObjectType * getObjectType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:8256
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition TypeBase.h:8277
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:8231
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition TypeBase.h:8271
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition Type.cpp:2011
qual_range quals() const
Definition TypeBase.h:8338
bool isObjCClassType() const
True if this is equivalent to the 'Class' type, i.e.
Definition TypeBase.h:8283
Represents one property declaration in an Objective-C interface.
Definition DeclObjC.h:734
bool isReadOnly() const
isReadOnly - Return true iff the property has a setter.
Definition DeclObjC.h:844
static ObjCPropertyDecl * findPropertyDecl(const DeclContext *DC, const IdentifierInfo *propertyID, ObjCPropertyQueryKind queryKind)
Lookup a property by name in the specified DeclContext.
Definition DeclObjC.cpp:176
bool isOptional() const
Definition DeclObjC.h:922
SetterKind getSetterKind() const
getSetterKind - Return the method used for doing assignment in the property setter.
Definition DeclObjC.h:879
Selector getSetterName() const
Definition DeclObjC.h:899
QualType getType() const
Definition DeclObjC.h:810
Selector getGetterName() const
Definition DeclObjC.h:891
ObjCPropertyAttribute::Kind getPropertyAttributes() const
Definition DeclObjC.h:821
ObjCPropertyImplDecl - Represents implementation declaration of a property in a class or category imp...
Definition DeclObjC.h:2811
ObjCIvarDecl * getPropertyIvarDecl() const
Definition DeclObjC.h:2885
Represents an Objective-C protocol declaration.
Definition DeclObjC.h:2090
protocol_range protocols() const
Definition DeclObjC.h:2167
bool isGNUFamily() const
Is this runtime basically of the GNU family of runtimes?
Represents the declaration of an Objective-C type parameter.
Definition DeclObjC.h:581
ObjCTypeParamVariance getVariance() const
Determine the variance of this type parameter.
Definition DeclObjC.h:626
Stores a list of Objective-C type parameters for a parameterized class or a category/extension thereo...
Definition DeclObjC.h:665
OffsetOfExpr - [C99 7.17] - This represents an expression of the form offsetof(record-type,...
Definition Expr.h:2596
const OffsetOfNode & getComponent(unsigned Idx) const
Definition Expr.h:2643
unsigned getNumComponents() const
Definition Expr.h:2651
Helper class for OffsetOfExpr.
Definition Expr.h:2490
@ Field
A field.
Definition Expr.h:2497
A structure for storing the information associated with an overloaded template name.
Represents a C++11 pack expansion that produces a sequence of expressions.
Definition ExprCXX.h:4417
A structure for storing a pack-index-template-name ([temp.names]).
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) const
ArrayRef< TemplateName > getExpansions() const
Sugar for parentheses used when specifying types.
Definition TypeBase.h:3383
void clear()
Clear parent maps.
DynTypedNodeList getParents(const NodeT &Node)
Returns the parents of the given node (within the traversal scope).
Represents a parameter to a function.
Definition Decl.h:1832
ObjCDeclQualifier getObjCDeclQualifier() const
Definition Decl.h:1896
QualType getOriginalType() const
Definition Decl.cpp:2974
ParsedAttr - Represents a syntactic attribute.
Definition ParsedAttr.h:119
Pointer-authentication qualifiers.
Definition TypeBase.h:153
static PointerAuthQualifier Create(unsigned Key, bool IsAddressDiscriminated, unsigned ExtraDiscriminator, PointerAuthenticationMode AuthenticationMode, bool IsIsaPointer, bool AuthenticatesNullValues)
Definition TypeBase.h:240
bool isEquivalent(PointerAuthQualifier Other) const
Definition TypeBase.h:302
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3403
QualType getPointeeType() const
Definition TypeBase.h:3413
PredefinedSugarKind Kind
Definition TypeBase.h:8489
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
A (possibly-)qualified type.
Definition TypeBase.h:938
bool hasAddressDiscriminatedPointerAuth() const
Definition TypeBase.h:1473
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8662
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition Type.cpp:3099
Qualifiers::GC getObjCGCAttr() const
Returns gc attribute of this type.
Definition TypeBase.h:8709
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8667
QualType getDesugaredType(const ASTContext &Context) const
Return the specified type with any "sugar" removed from the type.
Definition TypeBase.h:1312
QualType withConst() const
Definition TypeBase.h:1175
bool hasLocalQualifiers() const
Determine whether this particular QualType instance has any qualifiers, without looking through any t...
Definition TypeBase.h:1065
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8578
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8704
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8618
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1454
QualType getCanonicalType() const
Definition TypeBase.h:8630
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8672
SplitQualType split() const
Divides a QualType into its unqualified type and a set of local qualifiers.
Definition TypeBase.h:8599
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8651
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition TypeBase.h:1561
bool isCanonical() const
Definition TypeBase.h:8635
const Type * getTypePtrOrNull() const
Definition TypeBase.h:8582
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1348
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:3242
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition TypeBase.h:8610
Represents a template name as written in source code.
void Profile(llvm::FoldingSetNodeID &ID)
A qualifier set is used to build a set of qualifiers.
Definition TypeBase.h:8518
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition TypeBase.h:8525
The collection of all-type qualifiers we support.
Definition TypeBase.h:332
unsigned getCVRQualifiers() const
Definition TypeBase.h:489
void removeCVRQualifiers(unsigned mask)
Definition TypeBase.h:496
GC getObjCGCAttr() const
Definition TypeBase.h:520
void addAddressSpace(LangAS space)
Definition TypeBase.h:598
static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R)
Returns the common set of qualifiers while removing them from the given sets.
Definition TypeBase.h:385
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:362
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition TypeBase.h:355
@ OCL_None
There is no lifetime qualification on this type.
Definition TypeBase.h:351
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition TypeBase.h:365
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition TypeBase.h:368
void removeObjCLifetime()
Definition TypeBase.h:552
bool hasNonFastQualifiers() const
Return true if the set contains any qualifiers which require an ExtQuals node to be allocated.
Definition TypeBase.h:639
void addConsistentQualifiers(Qualifiers qs)
Add the qualifiers from the given set to this set, given that they don't conflict.
Definition TypeBase.h:690
void removeFastQualifiers(unsigned mask)
Definition TypeBase.h:625
bool hasUnaligned() const
Definition TypeBase.h:512
bool hasAddressSpace() const
Definition TypeBase.h:571
static bool isAddressSpaceSupersetOf(LangAS A, LangAS B, const ASTContext &Ctx)
Returns true if address space A is equal to or a superset of B.
Definition TypeBase.h:709
unsigned getFastQualifiers() const
Definition TypeBase.h:620
void removeAddressSpace()
Definition TypeBase.h:597
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:604
bool hasObjCGCAttr() const
Definition TypeBase.h:519
uint64_t getAsOpaqueValue() const
Definition TypeBase.h:456
bool hasObjCLifetime() const
Definition TypeBase.h:545
ObjCLifetime getObjCLifetime() const
Definition TypeBase.h:546
Qualifiers withoutObjCGCAttr() const
Definition TypeBase.h:529
bool empty() const
Definition TypeBase.h:648
void addObjCGCAttr(GC type)
Definition TypeBase.h:525
LangAS getAddressSpace() const
Definition TypeBase.h:572
An rvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3733
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:4506
bool isLambda() const
Determine whether this record is a class describing a lambda function object.
Definition Decl.cpp:5357
bool hasFlexibleArrayMember() const
Definition Decl.h:4539
field_range fields() const
Definition Decl.h:4709
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition Decl.cpp:5343
RecordDecl * getMostRecentDecl()
Definition Decl.h:4532
virtual void completeDefinition()
Note that the definition of this type is now complete.
Definition Decl.cpp:5402
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition Decl.h:4690
bool field_empty() const
Definition Decl.h:4717
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3678
QualType getPointeeType() const
Definition TypeBase.h:3700
This table allows us to fully hide how we implement multi-keyword caching.
std::string getAsString() const
Derive the full selector name (e.g.
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
This class handles loading and caching of source files into memory.
A trivial tuple used to represent a source range.
SourceLocation getBegin() const
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, bool Canonical, bool ProfileLambdaExpr=false) const
Produce a unique representation of the given statement.
The streaming interface shared between DiagnosticBuilder and PartialDiagnostic.
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1844
static StringLiteral * Create(const ASTContext &Ctx, StringRef Str, StringLiteralKind Kind, bool Pascal, QualType Ty, ArrayRef< SourceLocation > Locs)
This is the "fully general" constructor that allows representation of strings formed from one or more...
Definition Expr.cpp:1198
A structure for storing an already-substituted template template parameter pack.
Decl * getAssociatedDecl() const
A template-like entity which owns the whole pattern being substituted.
void Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context)
TemplateTemplateParmDecl * getParameterPack() const
Retrieve the template template parameter pack being substituted.
TemplateArgument getArgumentPack() const
Retrieve the template template argument pack with which this parameter was substituted.
unsigned getIndex() const
Returns the index of the replaced parameter in the associated declaration.
A structure for storing the information associated with a substituted template template parameter.
void Profile(llvm::FoldingSetNodeID &ID)
TemplateTemplateParmDecl * getParameter() const
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3898
TagTypeKind TagKind
Definition Decl.h:3903
TypedefNameDecl * getTypedefNameForAnonDecl() const
Definition Decl.h:4135
void startDefinition()
Starts the definition of this tag declaration.
Definition Decl.cpp:5017
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:5010
bool isUnion() const
Definition Decl.h:4109
TagKind getTagKind() const
Definition Decl.h:4098
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Kind
The basic C++ ABI kind.
static Kind getKind(StringRef Name)
Exposes information about the current target.
Definition TargetInfo.h:228
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
unsigned getMaxAtomicInlineWidth() const
Return the maximum width lock-free atomic operation which can be inlined given the supported features...
Definition TargetInfo.h:854
virtual LangAS getCUDABuiltinAddressSpace(unsigned AS) const
Map from the address space field in builtin description strings to the language address space.
virtual LangAS getOpenCLBuiltinAddressSpace(unsigned AS) const
Map from the address space field in builtin description strings to the language address space.
unsigned getDefaultAlignForAttributeAligned() const
Return the default alignment for attribute((aligned)) on this target, to be used if no alignment valu...
Definition TargetInfo.h:747
BuiltinVaListKind
The different kinds of __builtin_va_list types defined by the target implementation.
Definition TargetInfo.h:341
@ AArch64ABIBuiltinVaList
__builtin_va_list as defined by the AArch64 ABI http://infocenter.arm.com/help/topic/com....
Definition TargetInfo.h:350
@ PowerABIBuiltinVaList
__builtin_va_list as defined by the Power ABI: https://www.power.org /resources/downloads/Power-Arch-...
Definition TargetInfo.h:355
@ AAPCSABIBuiltinVaList
__builtin_va_list as defined by ARM AAPCS ABI http://infocenter.arm.com
Definition TargetInfo.h:364
@ CharPtrBuiltinVaList
typedef char* __builtin_va_list;
Definition TargetInfo.h:343
@ VoidPtrBuiltinVaList
typedef void* __builtin_va_list;
Definition TargetInfo.h:346
@ X86_64ABIBuiltinVaList
__builtin_va_list as defined by the x86-64 ABI: http://refspecs.linuxbase.org/elf/x86_64-abi-0....
Definition TargetInfo.h:359
virtual uint64_t getNullPointerValue(LangAS AddrSpace) const
Get integer value for null pointer.
Definition TargetInfo.h:513
static bool isTypeSigned(IntType T)
Returns true if the type is signed; false otherwise.
IntType getPtrDiffType(LangAS AddrSpace) const
Definition TargetInfo.h:415
bool isLittleEndian() const
IntType getSizeType() const
Definition TargetInfo.h:396
FloatModeKind getRealTypeByWidth(unsigned BitWidth, FloatModeKind ExplicitType) const
Return floating point type with specified width.
virtual IntType getIntTypeByWidth(unsigned BitWidth, bool IsSigned) const
Return integer type with specified width.
unsigned getMaxAlignedAttribute() const
Get the maximum alignment in bits for a static variable with aligned attribute.
Definition TargetInfo.h:974
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:755
unsigned getTargetAddressSpace(LangAS AS) const
IntType getSignedSizeType() const
Definition TargetInfo.h:397
const llvm::fltSemantics & getLongDoubleFormat() const
Definition TargetInfo.h:805
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
bool useAddressSpaceMapMangling() const
Specify if mangling based on address space map should be used or not for language specific address sp...
A convenient class for passing around template argument information.
ArrayRef< TemplateArgumentLoc > arguments() const
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
Location wrapper for a TemplateArgument.
Represents a template argument.
ArrayRef< TemplateArgument > getPackAsArray() const
Return the array of arguments in this template argument pack.
QualType getStructuralValueType() const
Get the type of a StructuralValue.
QualType getParamTypeForDecl() const
Expr * getAsExpr() const
Retrieve the template argument as an expression.
UnsignedOrNone getNumTemplateExpansions() const
Retrieve the number of expansions that a template template argument expansion will produce,...
QualType getAsType() const
Retrieve the type for a type template argument.
llvm::APSInt getAsIntegral() const
Retrieve the template argument as an integral value.
QualType getNullPtrType() const
Retrieve the type for null non-type template argument.
static TemplateArgument CreatePackCopy(ASTContext &Context, ArrayRef< TemplateArgument > Args)
Create a new template argument pack by copying the given set of template arguments.
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
bool structurallyEquals(const TemplateArgument &Other) const
Determines whether two template arguments are superficially the same.
QualType getIntegralType() const
Retrieve the type of the integral value.
bool getIsDefaulted() const
If returns 'true', this TemplateArgument corresponds to a default template parameter.
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
ArrayRef< TemplateArgument > pack_elements() const
Iterator range referencing all of the elements of a template argument pack.
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
@ Template
The template argument is a template name that was provided for a template template parameter.
@ StructuralValue
The template argument is a non-type template argument that can't be represented by the special-case D...
@ Pack
The template argument is actually a parameter pack.
@ TemplateExpansion
The template argument is a pack expansion of a template name that was provided for a template templat...
@ NullPtr
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
@ Type
The template argument is a type.
@ Null
Represents an empty template argument, e.g., one that has not been deduced.
@ Integral
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
ArgKind getKind() const
Return the kind of stored template argument.
TemplateName getAsTemplateOrTemplatePattern() const
Retrieve the template argument as a template name; if the argument is a pack expansion,...
const APValue & getAsStructuralValue() const
Get the value of a StructuralValue.
The base class of all kinds of template declarations (e.g., class, function, etc.).
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Represents a C++ template name within the type system.
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
DeducedTemplateStorage * getAsDeducedTemplateName() const
Retrieve the deduced template info, if any.
bool isNull() const
Determine whether this template name is NULL.
DependentTemplateName * getAsDependentTemplateName() const
Retrieve the underlying dependent template name structure, if any.
std::optional< TemplateName > desugar(bool IgnoreDeduced) const
OverloadedTemplateStorage * getAsOverloadedTemplate() const
Retrieve the underlying, overloaded function template declarations that this template name refers to,...
AssumedTemplateStorage * getAsAssumedTemplateName() const
Retrieve information on a name that has been assumed to be a template-name in order to permit a call ...
NameKind getKind() const
void * getAsVoidPointer() const
Retrieve the template name as a void pointer.
@ UsingTemplate
A template name that refers to a template declaration found through a specific using shadow declarati...
@ OverloadedTemplate
A set of overloaded template declarations.
@ PackIndexingTemplate
A pack-index-template-name.
@ Template
A single template declaration.
@ DependentTemplate
A dependent template name that has not been resolved to a template (or set of templates).
@ SubstTemplateTemplateParm
A template template parameter that has been substituted for some other template name.
@ SubstTemplateTemplateParmPack
A template template parameter pack that has been substituted for a template template argument pack,...
@ DeducedTemplate
A template name that refers to another TemplateName with deduced default arguments.
@ QualifiedTemplate
A qualified template name, where the qualification is kept to describe the source code as written.
@ AssumedTemplate
An unqualified-id that has been assumed to name a function template that will be found by ADL.
UsingShadowDecl * getAsUsingShadowDecl() const
Retrieve the using shadow declaration through which the underlying template declaration is introduced...
SubstTemplateTemplateParmPackStorage * getAsSubstTemplateTemplateParmPack() const
Retrieve the substituted template template parameter pack, if known.
SubstTemplateTemplateParmStorage * getAsSubstTemplateTemplateParm() const
Retrieve the substituted template template parameter, if known.
PackIndexingTemplateStorage * getAsPackIndexingTemplate() const
Retrieve the pack-index-template-name storage, if any.
A template parameter object.
static void Profile(llvm::FoldingSetNodeID &ID, QualType T, const APValue &V)
Stores a list of template parameters for a TemplateDecl and its derived classes.
NamedDecl * getParam(unsigned Idx)
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
NamedDecl *const * const_iterator
Iterates through the template parameters in this list.
Expr * getRequiresClause()
The constraint-expression of the associated requires-clause.
ArrayRef< NamedDecl * > asArray()
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
TemplateNameKind templateParameterKind() const
unsigned getPosition() const
Get the position of the template parameter within its parameter list.
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.
static TemplateTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation L, int D, int P, bool ParameterPack, IdentifierInfo *Id, TemplateNameKind ParameterKind, bool Typename, TemplateParameterList *Params)
unsigned getDepth() const
Get the nesting depth of the template parameter.
Declaration of a template type parameter.
static TemplateTypeParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc, SourceLocation NameLoc, int D, int P, IdentifierInfo *Id, bool Typename, bool ParameterPack, bool HasTypeConstraint=false, UnsignedOrNone NumExpanded=std::nullopt)
Token - This structure provides full information about a lexed token.
Definition Token.h:36
Models the abbreviated syntax to constrain a template type parameter: template <convertible_to<string...
Definition ASTConcept.h:224
Expr * getImmediatelyDeclaredConstraint() const
Get the immediately-declared constraint expression introduced by this type-constraint,...
Definition ASTConcept.h:241
TemplateName getNamedConcept() const
Definition ASTConcept.h:251
ConceptReference * getConceptReference() const
Definition ASTConcept.h:245
Represents a declaration of a type.
Definition Decl.h:3694
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type.
Definition TypeLoc.h:78
static unsigned getFullDataSizeForType(QualType Ty)
Returns the size of type source info data block for the given type.
Definition TypeLoc.cpp:95
void initialize(ASTContext &Context, SourceLocation Loc) const
Initializes this to state that every location in this type is the given location.
Definition TypeLoc.h:211
Represents a typeof (or typeof) expression (a C23 feature and GCC extension) or a typeof_unqual expre...
Definition TypeBase.h:6458
A container of type source information.
Definition TypeBase.h:8549
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:267
The base class of the type hierarchy.
Definition TypeBase.h:1879
bool isBlockPointerType() const
Definition TypeBase.h:8835
bool isVoidType() const
Definition TypeBase.h:9200
bool isObjCBuiltinType() const
Definition TypeBase.h:9045
bool isPackedVectorBoolType(const ASTContext &ctx) const
Definition Type.cpp:542
QualType getRVVEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an RVV builtin type.
Definition Type.cpp:2904
bool isIncompleteArrayType() const
Definition TypeBase.h:8922
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2394
bool isFloat16Type() const
Definition TypeBase.h:9213
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isConstantArrayType() const
Definition TypeBase.h:8918
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition Type.cpp:2652
bool isArrayType() const
Definition TypeBase.h:8914
bool isCharType() const
Definition Type.cpp:2321
bool isPointerType() const
Definition TypeBase.h:8815
TagDecl * castAsTagDecl() const
Definition Type.h:69
bool isArrayParameterType() const
Definition TypeBase.h:8930
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9248
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9498
bool isSignedFixedPointType() const
Return true if this is a fixed point type that is signed according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9292
bool isEnumeralType() const
Definition TypeBase.h:8946
bool isObjCQualifiedIdType() const
Definition TypeBase.h:9015
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:885
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9326
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition TypeBase.h:2980
bool isBitIntType() const
Definition TypeBase.h:9090
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8938
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2863
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9264
bool isHalfType() const
Definition TypeBase.h:9208
bool isSaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9280
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition TypeBase.h:2469
QualType getCanonicalTypeInternal() const
Definition TypeBase.h:3200
@ PtrdiffT
The "ptrdiff_t" type.
Definition TypeBase.h:2344
@ SizeT
The "size_t" type.
Definition TypeBase.h:2338
@ SignedSizeT
The signed integer type corresponding to "size_t".
Definition TypeBase.h:2341
bool isObjCIdType() const
Definition TypeBase.h:9027
bool isOverflowBehaviorType() const
Definition TypeBase.h:8986
bool isUnsaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9288
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9484
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2662
bool isFunctionType() const
Definition TypeBase.h:8811
bool isObjCObjectPointerType() const
Definition TypeBase.h:8994
bool isUnsignedFixedPointType() const
Return true if this is a fixed point type that is unsigned according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9306
bool isVectorType() const
Definition TypeBase.h:8954
bool isObjCClassType() const
Definition TypeBase.h:9033
bool isRVVVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'riscv_rvv_vector_bits' type attribute,...
Definition Type.cpp:2886
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition Type.cpp:2823
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:3002
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:2462
bool isAnyPointerType() const
Definition TypeBase.h:8823
TypeClass getTypeClass() const
Definition TypeBase.h:2449
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition TypeBase.h:2475
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9431
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition Type.cpp:786
bool isNullPtrType() const
Definition TypeBase.h:9241
bool isRecordType() const
Definition TypeBase.h:8942
bool isObjCRetainableType() const
Definition Type.cpp:5616
NullabilityKindOrNone getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5332
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition Decl.h:3848
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition Decl.cpp:5876
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3743
QualType getUnderlyingType() const
Definition Decl.h:3798
static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TypedefNameDecl *Decl, QualType Underlying)
Definition TypeBase.h:6402
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2313
Opcode getOpcode() const
Definition Expr.h:2349
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
Definition DeclCXX.h:4525
static void Profile(llvm::FoldingSetNodeID &ID, QualType Ty, const APValue &APVal)
Definition DeclCXX.h:4553
The iterator over UnresolvedSets.
Represents the dependent type named by a dependently-scoped typename using declaration,...
Definition TypeBase.h:6263
static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const UnresolvedUsingTypenameDecl *D)
Definition TypeBase.h:6300
Represents a dependent using declaration which was marked with typename.
Definition DeclCXX.h:4084
UnresolvedUsingTypenameDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this declaration.
Definition DeclCXX.h:4149
Represents a C++ using-enum-declaration.
Definition DeclCXX.h:3839
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3446
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition DeclCXX.h:3510
BaseUsingDecl * getIntroducer() const
Gets the (written or instantiated) using declaration that introduced this declaration.
Definition DeclCXX.cpp:3487
static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const UsingShadowDecl *D, QualType UnderlyingType)
Definition TypeBase.h:6340
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:714
void setType(QualType newType)
Definition Decl.h:726
QualType getType() const
Definition Decl.h:725
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition Decl.cpp:5691
void clear()
Definition Value.cpp:217
Represents a variable declaration or definition.
Definition Decl.h:934
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition Decl.cpp:2804
bool hasInit() const
Definition Decl.cpp:2402
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:2465
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1308
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition Decl.h:1216
bool isInline() const
Whether this variable is (C++1z) inline.
Definition Decl.h:1588
@ DeclarationOnly
This declaration is only a declaration.
Definition Decl.h:1320
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition Decl.cpp:2379
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:2773
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:4064
Expr * getSizeExpr() const
Definition TypeBase.h:4078
Represents a GCC generic vector type.
Definition TypeBase.h:4398
unsigned getNumElements() const
Definition TypeBase.h:4413
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:4429
VectorKind getVectorKind() const
Definition TypeBase.h:4418
QualType getElementType() const
Definition TypeBase.h:4412
A full comment attached to a declaration, contains block content.
Definition Comment.h:1097
ArrayRef< BlockContentComment * > getBlocks() const
Definition Comment.h:1135
const DeclInfo * getDeclInfo() const LLVM_READONLY
Definition Comment.h:1129
const Decl * getDecl() const LLVM_READONLY
Definition Comment.h:1125
Holds all information required to evaluate constexpr code in a module.
Definition Context.h:49
Defines the Linkage enumeration and various utility functions.
Defines the clang::TargetInfo interface.
Definition SPIR.cpp:47
mlir::Type getBaseType(mlir::Value varPtr)
const AstTypeMatcher< TagType > tagType
SmallVector< BoundNodes, 1 > match(MatcherT Matcher, const NodeT &Node, ASTContext &Context)
Returns the results of matching Matcher on Node.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const AstTypeMatcher< ArrayType > arrayType
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
Top level wrappers for InstallAPI frontend operations.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus20
@ CPlusPlus
@ CPlusPlus17
GVALinkage
A more specific kind of linkage than enum Linkage.
Definition Linkage.h:72
@ GVA_StrongODR
Definition Linkage.h:77
@ GVA_StrongExternal
Definition Linkage.h:76
@ GVA_AvailableExternally
Definition Linkage.h:74
@ GVA_DiscardableODR
Definition Linkage.h:75
@ GVA_Internal
Definition Linkage.h:73
AutoTypeKeyword
Which keyword(s) were used to create an AutoType.
Definition TypeBase.h:1838
OpenCLTypeKind
OpenCL type kinds.
Definition TargetInfo.h:214
@ OCLTK_ReserveID
Definition TargetInfo.h:221
@ OCLTK_Sampler
Definition TargetInfo.h:222
@ OCLTK_Pipe
Definition TargetInfo.h:219
@ OCLTK_ClkEvent
Definition TargetInfo.h:216
@ OCLTK_Event
Definition TargetInfo.h:217
@ OCLTK_Default
Definition TargetInfo.h:215
@ OCLTK_Queue
Definition TargetInfo.h:220
bool isRVVFixedLengthDataVectorKind(VectorKind VK)
True if VK is one of the RVV fixed-length data vector kinds, i.e.
Definition TypeBase.h:4316
constexpr llvm::StringLiteral VTTVTablePointerDiscriminatorSuffix
FunctionType::ExtInfo getFunctionExtInfo(const Type &t)
Definition TypeBase.h:8713
Stmt Stmt * Callback
Definition StmtOpenMP.h:930
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
NullabilityKind
Describes the nullability of a particular type.
Definition Specifiers.h:350
@ Nullable
Values of this type can be null.
Definition Specifiers.h:354
@ Unspecified
Whether values of this type can be null is (explicitly) unspecified.
Definition Specifiers.h:359
@ NonNull
Values of this type can never be null.
Definition Specifiers.h:352
@ ICIS_NoInit
No in-class initializer.
Definition Specifiers.h:276
@ TemplateName
The identifier is a template name. FIXME: Add an annotation for that.
Definition Parser.h:61
std::pair< FileID, unsigned > FileIDAndOffset
CXXABI * CreateMicrosoftCXXABI(ASTContext &Ctx)
@ Vector
'vector' clause, allowed on 'loop', Combined, and 'routine' directives.
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
TypeOfKind
The kind of 'typeof' expression we're after.
Definition TypeBase.h:919
@ AS_public
Definition Specifiers.h:128
SmallVector< Attr *, 4 > AttrVec
AttrVec - A vector of Attr, which is how they are stored on the AST.
unsigned getRVVFixedLengthMaskRatioLog2(VectorKind VK)
Return log2 of the R of the vbool<R>_t type recorded in an RVV fixed-length mask vector kind: Ratio1 ...
Definition TypeBase.h:4345
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
@ SC_Register
Definition Specifiers.h:261
@ SC_Static
Definition Specifiers.h:256
bool isRVVFixedLengthVectorKind(VectorKind VK)
True if VK is one of the RVV fixed-length data or mask vector kinds.
Definition TypeBase.h:4352
CXXABI * CreateItaniumCXXABI(ASTContext &Ctx)
Creates an instance of a C++ ABI class.
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have.
Definition Linkage.h:24
@ External
External linkage, which indicates that the entity can be referred to from other translation units.
Definition Linkage.h:58
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition ASTLambda.h:28
@ Result
The result type of a method or function.
Definition TypeBase.h:906
@ TypeAlignment
Definition TypeBase.h:77
ArraySizeModifier
Capture whether this is a normal array (e.g.
Definition TypeBase.h:3817
OptionalUnsigned< unsigned > UnsignedOrNone
const FunctionProtoType * T
bool isComputedNoexcept(ExceptionSpecificationType ESpecType)
@ Template
We are parsing a template declaration.
Definition Parser.h:81
@ Interface
The "__interface" keyword.
Definition TypeBase.h:6176
@ Struct
The "struct" keyword.
Definition TypeBase.h:6173
@ Class
The "class" keyword.
Definition TypeBase.h:6182
constexpr uint16_t SelPointerConstantDiscriminator
Constant discriminator to be used with objective-c sel pointers.
bool isDiscardableGVALinkage(GVALinkage L)
Definition Linkage.h:80
BuiltinTemplateKind
Kinds of BuiltinTemplateDecl.
Definition Builtins.h:508
@ Keyword
The name has been typo-corrected to a keyword.
Definition Sema.h:556
LangAS
Defines the address space values used by the address space qualifier of QualType.
TranslationUnitKind
Describes the kind of translation unit being processed.
DeducedKind
Definition TypeBase.h:1811
@ Deduced
The normal deduced case.
Definition TypeBase.h:1818
@ Undeduced
Not deduced yet. This is for example an 'auto' which was just parsed.
Definition TypeBase.h:1813
const Decl & adjustDeclToTemplate(const Decl &D)
If we have a 'templated' declaration for a template, adjust 'D' to refer to the actual template.
FloatModeKind
Definition TargetInfo.h:76
bool isPtrSizeAddressSpace(LangAS AS)
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:136
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:139
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition Specifiers.h:148
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:143
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1306
const StreamingDiagnostic & operator<<(const StreamingDiagnostic &DB, const ConceptReference *C)
Insertion operator for diagnostics.
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition Specifiers.h:192
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition Specifiers.h:210
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition Specifiers.h:206
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:202
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:198
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition Specifiers.h:195
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:282
@ CC_M68kRTD
Definition Specifiers.h:302
@ CC_X86RegCall
Definition Specifiers.h:291
@ CC_X86VectorCall
Definition Specifiers.h:287
@ CC_X86StdCall
Definition Specifiers.h:284
@ CC_X86FastCall
Definition Specifiers.h:285
@ Invariant
The parameter is invariant: must match exactly.
Definition DeclObjC.h:558
@ Contravariant
The parameter is contravariant, e.g., X<T> is a subtype of X when the type parameter is covariant and...
Definition DeclObjC.h:566
@ Covariant
The parameter is covariant, e.g., X<T> is a subtype of X when the type parameter is covariant and T i...
Definition DeclObjC.h:562
@ AltiVecBool
is AltiVec 'vector bool ...'
Definition TypeBase.h:4243
@ SveFixedLengthData
is AArch64 SVE fixed-length data vector
Definition TypeBase.h:4252
@ AltiVecPixel
is AltiVec 'vector Pixel'
Definition TypeBase.h:4240
@ Generic
not a target-specific vector type
Definition TypeBase.h:4234
@ SveFixedLengthPredicate
is AArch64 SVE fixed-length predicate vector
Definition TypeBase.h:4255
U cast(CodeGen::Address addr)
Definition Address.h:327
LangAS getLangASFromTargetAS(unsigned TargetAS)
AlignRequirementKind
Definition ASTContext.h:174
@ ResistPragmaPack
The type's natural alignment is preserved under pragma pack in MSVC record layout (e....
Definition ASTContext.h:189
@ None
The alignment was not explicit in code.
Definition ASTContext.h:176
@ RequiredByEnum
The alignment comes from an alignment attribute on a enum type.
Definition ASTContext.h:185
@ RequiredByTypedef
The alignment comes from an alignment attribute on a typedef.
Definition ASTContext.h:179
@ RequiredByRecord
The alignment comes from an alignment attribute on a record type.
Definition ASTContext.h:182
@ PackIndex
Index of a pack indexing expression or specifier.
Definition Sema.h:845
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition TypeBase.h:6146
@ Interface
The "__interface" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6151
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:6167
@ Struct
The "struct" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6148
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6157
@ Union
The "union" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6154
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6160
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition TypeBase.h:6164
ExceptionSpecificationType
The various types of exception specifications that exist in C++11.
@ EST_DependentNoexcept
noexcept(expression), value-dependent
@ EST_Uninstantiated
not instantiated yet
@ EST_Unparsed
not parsed yet
@ EST_NoThrow
Microsoft __declspec(nothrow) extension.
@ EST_None
no exception specification
@ EST_MSAny
Microsoft throw(...) extension.
@ EST_BasicNoexcept
noexcept
@ EST_NoexceptFalse
noexcept(expression), evals to 'false'
@ EST_Unevaluated
not evaluated yet, for special member function
@ EST_NoexceptTrue
noexcept(expression), evals to 'true'
@ EST_Dynamic
throw(T1, T2)
bool isRVVFixedLengthMaskVectorKind(VectorKind VK)
True if VK is one of the RVV fixed-length mask vector kinds, i.e.
Definition TypeBase.h:4338
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t int64_t
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t uint64_t __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 uint64_t
unsigned NumTemplateArgs
The number of template arguments in TemplateArgs.
const Expr * ConstraintExpr
Definition Decl.h:90
UnsignedOrNone ArgPackSubstIndex
Definition Decl.h:91
Copy initialization expr of a __block variable and a boolean flag that indicates whether the expressi...
Definition Expr.h:6804
Expr * getCopyExpr() const
Definition Expr.h:6811
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
ArrayRef< TemplateArgument > Args
Holds information about the various types of exception specification.
Definition TypeBase.h:5605
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition TypeBase.h:5607
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition TypeBase.h:5610
Expr * NoexceptExpr
Noexcept expression, if this is a computed noexcept specification.
Definition TypeBase.h:5613
Extra information about a function prototype.
Definition TypeBase.h:5633
bool requiresFunctionProtoTypeArmAttributes() const
Definition TypeBase.h:5679
const ExtParameterInfo * ExtParameterInfos
Definition TypeBase.h:5638
bool requiresFunctionProtoTypeExtraAttributeInfo() const
Definition TypeBase.h:5683
bool requiresFunctionProtoTypeExtraBitfields() const
Definition TypeBase.h:5672
const IdentifierInfo * getIdentifier() const
Returns the identifier to which this template name refers.
OverloadedOperatorKind getOperator() const
Return the overloaded operator to which this template name refers.
static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag)
Converts a TagTypeKind into an elaborated type keyword.
Definition Type.cpp:3525
A late-parsed attribute that will be applied as a type attribute.
Definition Parser.h:238
constexpr underlying_type toInternalRepresentation() const
Contains information gathered from parsing the contents of TargetAttr.
Definition TargetInfo.h:59
A std::pair-like structure for storing a qualified type split into its local qualifiers and its local...
Definition TypeBase.h:871
const Type * Ty
The locally-unqualified type.
Definition TypeBase.h:873
Qualifiers Quals
The local qualifiers.
Definition TypeBase.h:876
llvm::DenseSet< std::tuple< Decl *, Decl *, int > > NonEquivalentDeclSet
Store declaration pairs already found to be non-equivalent.
bool IsEquivalent(Decl *D1, Decl *D2)
Determine whether the two declarations are structurally equivalent.
A this pointer adjustment.
Definition Thunk.h:92
IntType
===-— Target Data Type Query Methods ----------------------------—===//
Definition TargetInfo.h:148
AlignRequirementKind AlignRequirement
Definition ASTContext.h:210
bool isAlignRequired()
Definition ASTContext.h:201
AlignRequirementKind AlignRequirement
Definition ASTContext.h:195
Information about the declaration, useful to clients of FullComment.
Definition Comment.h:974
const TemplateParameterList * TemplateParameters
Template parameters that can be referenced by \tparam if CommentDecl is a template (IsTemplateDecl or...
Definition Comment.h:1000
const Decl * CommentDecl
Declaration the comment is actually attached to (in the source).
Definition Comment.h:977