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"
21#include "clang/AST/Attr.h"
23#include "clang/AST/CharUnits.h"
24#include "clang/AST/Comment.h"
25#include "clang/AST/Decl.h"
26#include "clang/AST/DeclBase.h"
27#include "clang/AST/DeclCXX.h"
29#include "clang/AST/DeclObjC.h"
34#include "clang/AST/Expr.h"
35#include "clang/AST/ExprCXX.h"
37#include "clang/AST/Mangle.h"
43#include "clang/AST/Stmt.h"
46#include "clang/AST/Type.h"
47#include "clang/AST/TypeLoc.h"
56#include "clang/Basic/LLVM.h"
58#include "clang/Basic/Linkage.h"
59#include "clang/Basic/Module.h"
69#include "clang/Lex/MacroInfo.h"
70#include "llvm/ADT/APFixedPoint.h"
71#include "llvm/ADT/APInt.h"
72#include "llvm/ADT/APSInt.h"
73#include "llvm/ADT/ArrayRef.h"
74#include "llvm/ADT/DenseMap.h"
75#include "llvm/ADT/DenseSet.h"
76#include "llvm/ADT/FoldingSet.h"
77#include "llvm/ADT/PointerUnion.h"
78#include "llvm/ADT/STLExtras.h"
79#include "llvm/ADT/SmallPtrSet.h"
80#include "llvm/ADT/SmallVector.h"
81#include "llvm/ADT/StringExtras.h"
82#include "llvm/ADT/StringRef.h"
83#include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
84#include "llvm/Support/Capacity.h"
85#include "llvm/Support/Casting.h"
86#include "llvm/Support/Compiler.h"
87#include "llvm/Support/ErrorHandling.h"
88#include "llvm/Support/MD5.h"
89#include "llvm/Support/MathExtras.h"
90#include "llvm/Support/SipHash.h"
91#include "llvm/Support/raw_ostream.h"
92#include "llvm/TargetParser/AArch64TargetParser.h"
93#include "llvm/TargetParser/Triple.h"
94#include <algorithm>
95#include <cassert>
96#include <cstddef>
97#include <cstdint>
98#include <cstdlib>
99#include <map>
100#include <memory>
101#include <optional>
102#include <string>
103#include <tuple>
104#include <utility>
105
106using namespace clang;
107
118
119/// \returns The locations that are relevant when searching for Doc comments
120/// related to \p Key.
123 SourceManager &SourceMgr) {
124 if (const auto *MI = dyn_cast<const MacroInfo *>(Key)) {
125 SourceLocation DefLoc = MI->getDefinitionLoc();
126 if (DefLoc.isInvalid() || !DefLoc.isFileID())
127 return {};
128
129 // The macro's definition location points at its name (e.g. FOO in
130 // `#define FOO 1`). The text between a preceding documentation comment
131 // and the name contains the `#define` directive itself, which would be
132 // rejected by the preprocessor-directive guard in
133 // getRawCommentNoCacheImpl. Walk back to the leading `#` so that
134 // the guard only fires when something *else* sits between the comment
135 // and our directive.
136 FileIDAndOffset Decomposed = SourceMgr.getDecomposedLoc(DefLoc);
137 bool Invalid = false;
138 StringRef Buffer = SourceMgr.getBufferData(Decomposed.first, &Invalid);
139 if (Invalid)
140 return {};
141 unsigned Offset = Decomposed.second;
142 if (size_t Found = Buffer.find_last_of("#\n", Offset);
143 Found != StringRef::npos)
144 Offset = Found;
145 return {SourceMgr.getLocForStartOfFile(Decomposed.first)
146 .getLocWithOffset(Offset)};
147 }
148
149 const auto *D = cast<const Decl *>(Key);
150 assert(D);
151
152 // User can not attach documentation to implicit declarations.
153 if (D->isImplicit())
154 return {};
155
156 // User can not attach documentation to implicit instantiations.
157 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
158 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
159 return {};
160 }
161
162 if (const auto *VD = dyn_cast<VarDecl>(D)) {
163 if (VD->isStaticDataMember() &&
164 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
165 return {};
166 }
167
168 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
169 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
170 return {};
171 }
172
173 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
174 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
175 if (TSK == TSK_ImplicitInstantiation ||
176 TSK == TSK_Undeclared)
177 return {};
178 }
179
180 if (const auto *ED = dyn_cast<EnumDecl>(D)) {
181 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
182 return {};
183 }
184 if (const auto *TD = dyn_cast<TagDecl>(D)) {
185 // When tag declaration (but not definition!) is part of the
186 // decl-specifier-seq of some other declaration, it doesn't get comment
187 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
188 return {};
189 }
190 // TODO: handle comments for function parameters properly.
191 if (isa<ParmVarDecl>(D))
192 return {};
193
194 // TODO: we could look up template parameter documentation in the template
195 // documentation.
199 return {};
200
202 // Find declaration location.
203 // For Objective-C declarations we generally don't expect to have multiple
204 // declarators, thus use declaration starting location as the "declaration
205 // location".
206 // For all other declarations multiple declarators are used quite frequently,
207 // so we use the location of the identifier as the "declaration location".
208 SourceLocation BaseLocation;
212 // Allow association with Y across {} in `typedef struct X {} Y`.
214 BaseLocation = D->getBeginLoc();
215 else
216 BaseLocation = D->getLocation();
217
218 if (!D->getLocation().isMacroID()) {
219 Locations.emplace_back(BaseLocation);
220 } else {
221 const auto *DeclCtx = D->getDeclContext();
222
223 // When encountering definitions generated from a macro (that are not
224 // contained by another declaration in the macro) we need to try and find
225 // the comment at the location of the expansion but if there is no comment
226 // there we should retry to see if there is a comment inside the macro as
227 // well. To this end we return first BaseLocation to first look at the
228 // expansion site, the second value is the spelling location of the
229 // beginning of the declaration defined inside the macro.
230 if (!(DeclCtx &&
231 Decl::castFromDeclContext(DeclCtx)->getLocation().isMacroID())) {
232 Locations.emplace_back(SourceMgr.getExpansionLoc(BaseLocation));
233 }
234
235 // We use Decl::getBeginLoc() and not just BaseLocation here to ensure that
236 // we don't refer to the macro argument location at the expansion site (this
237 // can happen if the name's spelling is provided via macro argument), and
238 // always to the declaration itself.
239 Locations.emplace_back(SourceMgr.getSpellingLoc(D->getBeginLoc()));
240 }
241
242 return Locations;
243}
244
246 RawCommentLookupKey Key, const SourceLocation RepresentativeLoc,
247 const std::map<unsigned, RawComment *> &CommentsInTheFile) const {
248 // If the declaration doesn't map directly to a location in a file, we
249 // can't find the comment.
250 if (RepresentativeLoc.isInvalid() || !RepresentativeLoc.isFileID())
251 return nullptr;
252
253 // If there are no comments anywhere, we won't find anything.
254 if (CommentsInTheFile.empty())
255 return nullptr;
256
257 const auto *D = dyn_cast<const Decl *>(Key);
258 const bool IsMacro = isa<const MacroInfo *>(Key);
259
260 // Decompose the location for the declaration and find the beginning of the
261 // file buffer.
262 const FileIDAndOffset LocDecomp =
263 SourceMgr.getDecomposedLoc(RepresentativeLoc);
264
265 // Slow path.
266 auto OffsetCommentBehindDecl =
267 CommentsInTheFile.lower_bound(LocDecomp.second);
268
269 // First check whether we have a trailing comment.
270 if (OffsetCommentBehindDecl != CommentsInTheFile.end()) {
271 RawComment *CommentBehindDecl = OffsetCommentBehindDecl->second;
272 if ((CommentBehindDecl->isDocumentation() ||
273 LangOpts.CommentOpts.ParseAllComments) &&
274 CommentBehindDecl->isTrailingComment() &&
275 (IsMacro || (D && (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) ||
277 isa<ObjCPropertyDecl>(D))))) {
278
279 // Check that Doxygen trailing comment comes after the declaration, starts
280 // on the same line and in the same file as the declaration.
281 if (SourceMgr.getLineNumber(LocDecomp.first, LocDecomp.second) ==
282 Comments.getCommentBeginLine(CommentBehindDecl, LocDecomp.first,
283 OffsetCommentBehindDecl->first)) {
284 return CommentBehindDecl;
285 }
286 }
287 }
288
289 // The comment just after the declaration was not a trailing comment.
290 // Let's look at the previous comment.
291 if (OffsetCommentBehindDecl == CommentsInTheFile.begin())
292 return nullptr;
293
294 auto OffsetCommentBeforeDecl = --OffsetCommentBehindDecl;
295 RawComment *CommentBeforeDecl = OffsetCommentBeforeDecl->second;
296
297 // Check that we actually have a non-member Doxygen comment.
298 if (!(CommentBeforeDecl->isDocumentation() ||
299 LangOpts.CommentOpts.ParseAllComments) ||
300 CommentBeforeDecl->isTrailingComment())
301 return nullptr;
302
303 // Decompose the end of the comment.
304 const unsigned CommentEndOffset =
305 Comments.getCommentEndOffset(CommentBeforeDecl);
306
307 // Get the corresponding buffer.
308 bool Invalid = false;
309 const char *Buffer =
310 SourceMgr.getBufferData(LocDecomp.first, &Invalid).data();
311 if (Invalid)
312 return nullptr;
313
314 // Extract text between the comment and declaration.
315 StringRef Text(Buffer + CommentEndOffset,
316 LocDecomp.second - CommentEndOffset);
317
318 // There should be no other declarations or preprocessor directives between
319 // comment and declaration.
320 if (Text.find_last_of(";{}#@") != StringRef::npos)
321 return nullptr;
322
323 return CommentBeforeDecl;
324}
325
327 const auto Locs = getLocsForCommentSearch(Key, SourceMgr);
328
329 for (const auto Loc : Locs) {
330 // If the declaration or macro doesn't map directly to a location in a file,
331 // we can't find the comment.
332 if (Loc.isInvalid() || !Loc.isFileID())
333 continue;
334
336 ExternalSource->ReadComments();
337 CommentsLoaded = true;
338 }
339
340 if (Comments.empty())
341 continue;
342
343 const FileID File = SourceMgr.getDecomposedLoc(Loc).first;
344 if (!File.isValid())
345 continue;
346
347 const auto CommentsInThisFile = Comments.getCommentsInFile(File);
348 if (!CommentsInThisFile || CommentsInThisFile->empty())
349 continue;
350
351 if (RawComment *Comment =
352 getRawCommentNoCacheImpl(Key, Loc, *CommentsInThisFile))
353 return Comment;
354 }
355
356 return nullptr;
357}
358
360 assert(LangOpts.RetainCommentsFromSystemHeaders ||
361 !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin()));
362 Comments.addComment(RC, LangOpts.CommentOpts, BumpAlloc);
363}
364
365const RawComment *
367 const Decl **OriginalDecl) const {
368 if (Key.isNull()) {
369 if (OriginalDecl)
370 *OriginalDecl = nullptr;
371 return nullptr;
372 }
373
374 // Macros have no redeclaration chain: look up directly, populate the cache,
375 // and return.
376 if (const auto *MI = dyn_cast<const MacroInfo *>(Key)) {
377 if (OriginalDecl)
378 *OriginalDecl = nullptr;
379 auto Existing = RawComments.find(Key);
380 if (Existing != RawComments.end())
381 return Existing->second;
382 if (const RawComment *RC = getRawCommentNoCache(Key)) {
383 cacheRawComment(MI, *RC);
384 return RC;
385 }
386 return nullptr;
387 }
388
389 const Decl *D = cast<const Decl *>(Key);
390 D = &adjustDeclToTemplate(*D);
391
392 // Any comment directly attached to D?
393 {
394 auto DeclComment = RawComments.find(D);
395 if (DeclComment != RawComments.end()) {
396 if (OriginalDecl)
397 *OriginalDecl = D;
398 return DeclComment->second;
399 }
400 }
401
402 // Any comment attached to any redeclaration of D?
403 const Decl *CanonicalD = D->getCanonicalDecl();
404 if (!CanonicalD)
405 return nullptr;
406
407 {
408 auto RedeclComment = RedeclChainComments.find(CanonicalD);
409 if (RedeclComment != RedeclChainComments.end()) {
410 if (OriginalDecl)
411 *OriginalDecl = RedeclComment->second;
412 auto CommentAtRedecl = RawComments.find(RedeclComment->second);
413 assert(CommentAtRedecl != RawComments.end() &&
414 "This decl is supposed to have comment attached.");
415 return CommentAtRedecl->second;
416 }
417 }
418
419 // Any redeclarations of D that we haven't checked for comments yet?
420 const Decl *LastCheckedRedecl = [&]() {
421 const Decl *LastChecked = CommentlessRedeclChains.lookup(CanonicalD);
422 bool CanUseCommentlessCache = false;
423 if (LastChecked) {
424 for (auto *Redecl : CanonicalD->redecls()) {
425 if (Redecl == D) {
426 CanUseCommentlessCache = true;
427 break;
428 }
429 if (Redecl == LastChecked)
430 break;
431 }
432 }
433 // FIXME: This could be improved so that even if CanUseCommentlessCache
434 // is false, once we've traversed past CanonicalD we still skip ahead
435 // LastChecked.
436 return CanUseCommentlessCache ? LastChecked : nullptr;
437 }();
438
439 for (const Decl *Redecl : D->redecls()) {
440 assert(Redecl);
441 // Skip all redeclarations that have been checked previously.
442 if (LastCheckedRedecl) {
443 if (LastCheckedRedecl == Redecl) {
444 LastCheckedRedecl = nullptr;
445 }
446 continue;
447 }
448 const RawComment *RedeclComment = getRawCommentNoCache(Redecl);
449 if (RedeclComment) {
450 cacheRawComment(Redecl, *RedeclComment);
451 if (OriginalDecl)
452 *OriginalDecl = Redecl;
453 return RedeclComment;
454 }
455 CommentlessRedeclChains[CanonicalD] = Redecl;
456 }
457
458 if (OriginalDecl)
459 *OriginalDecl = nullptr;
460 return nullptr;
461}
462
464 const RawComment &Comment) const {
465 assert(Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
466 RawComments.try_emplace(Original, &Comment);
467 if (const auto *D = dyn_cast<const Decl *>(Original)) {
468 const Decl *const CanonicalDecl = D->getCanonicalDecl();
469 RedeclChainComments.try_emplace(CanonicalDecl, D);
470 CommentlessRedeclChains.erase(CanonicalDecl);
471 }
472}
473
474static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
476 const DeclContext *DC = ObjCMethod->getDeclContext();
477 if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) {
478 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
479 if (!ID)
480 return;
481 // Add redeclared method here.
482 for (const auto *Ext : ID->known_extensions()) {
483 if (ObjCMethodDecl *RedeclaredMethod =
484 Ext->getMethod(ObjCMethod->getSelector(),
485 ObjCMethod->isInstanceMethod()))
486 Redeclared.push_back(RedeclaredMethod);
487 }
488 }
489}
490
492 const Preprocessor *PP) {
493 if (Comments.empty() || Decls.empty())
494 return;
495
496 FileID File;
497 for (const Decl *D : Decls) {
498 if (D->isInvalidDecl())
499 continue;
500
501 D = &adjustDeclToTemplate(*D);
502 SourceLocation Loc = D->getLocation();
503 if (Loc.isValid()) {
504 // See if there are any new comments that are not attached to a decl.
505 // The location doesn't have to be precise - we care only about the file.
506 File = SourceMgr.getDecomposedLoc(Loc).first;
507 break;
508 }
509 }
510
511 if (File.isInvalid())
512 return;
513
514 auto CommentsInThisFile = Comments.getCommentsInFile(File);
515 if (!CommentsInThisFile || CommentsInThisFile->empty() ||
516 CommentsInThisFile->rbegin()->second->isAttached())
517 return;
518
519 // There is at least one comment not attached to a decl.
520 // Maybe it should be attached to one of Decls?
521 //
522 // Note that this way we pick up not only comments that precede the
523 // declaration, but also comments that *follow* the declaration -- thanks to
524 // the lookahead in the lexer: we've consumed the semicolon and looked
525 // ahead through comments.
526 for (const Decl *D : Decls) {
527 assert(D);
528 if (D->isInvalidDecl())
529 continue;
530
531 D = &adjustDeclToTemplate(*D);
532
533 if (RawComments.count(D) > 0)
534 continue;
535
536 const auto DeclLocs = getLocsForCommentSearch(D, SourceMgr);
537
538 for (const auto DeclLoc : DeclLocs) {
539 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
540 continue;
541
542 if (RawComment *const DocComment =
543 getRawCommentNoCacheImpl(D, DeclLoc, *CommentsInThisFile)) {
544 cacheRawComment(D, *DocComment);
545 comments::FullComment *FC = DocComment->parse(*this, PP, D);
546 ParsedComments[D->getCanonicalDecl()] = FC;
547 break;
548 }
549 }
550 }
551}
552
554 const Decl *D) const {
555 auto *ThisDeclInfo = new (*this) comments::DeclInfo;
556 ThisDeclInfo->CommentDecl = D;
557 ThisDeclInfo->IsFilled = false;
558 ThisDeclInfo->fill();
559 ThisDeclInfo->CommentDecl = FC->getDecl();
560 if (!ThisDeclInfo->TemplateParameters)
561 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
563 new (*this) comments::FullComment(FC->getBlocks(),
564 ThisDeclInfo);
565 return CFC;
566}
567
569 const RawComment *RC = getRawCommentNoCache(D);
570 return RC ? RC->parse(*this, nullptr, D) : nullptr;
571}
572
574 const Decl *D,
575 const Preprocessor *PP) const {
576 if (!D || D->isInvalidDecl())
577 return nullptr;
578 D = &adjustDeclToTemplate(*D);
579
580 const Decl *Canonical = D->getCanonicalDecl();
581 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
582 ParsedComments.find(Canonical);
583
584 if (Pos != ParsedComments.end()) {
585 if (Canonical != D) {
586 comments::FullComment *FC = Pos->second;
588 return CFC;
589 }
590 return Pos->second;
591 }
592
593 const Decl *OriginalDecl = nullptr;
594
595 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
596 if (!RC) {
599 const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
600 if (OMD && OMD->isPropertyAccessor())
601 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
602 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
603 return cloneFullComment(FC, D);
604 if (OMD)
605 addRedeclaredMethods(OMD, Overridden);
606 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
607 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
608 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
609 return cloneFullComment(FC, D);
610 }
611 else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
612 // Attach any tag type's documentation to its typedef if latter
613 // does not have one of its own.
614 QualType QT = TD->getUnderlyingType();
615 if (const auto *TT = QT->getAs<TagType>())
616 if (comments::FullComment *FC = getCommentForDecl(TT->getDecl(), PP))
617 return cloneFullComment(FC, D);
618 }
619 else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
620 while (IC->getSuperClass()) {
621 IC = IC->getSuperClass();
623 return cloneFullComment(FC, D);
624 }
625 }
626 else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) {
627 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
629 return cloneFullComment(FC, D);
630 }
631 else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
632 if (!(RD = RD->getDefinition()))
633 return nullptr;
634 // Check non-virtual bases.
635 for (const auto &I : RD->bases()) {
636 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
637 continue;
638 QualType Ty = I.getType();
639 if (Ty.isNull())
640 continue;
642 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
643 continue;
644
646 return cloneFullComment(FC, D);
647 }
648 }
649 // Check virtual bases.
650 for (const auto &I : RD->vbases()) {
651 if (I.getAccessSpecifier() != AS_public)
652 continue;
653 QualType Ty = I.getType();
654 if (Ty.isNull())
655 continue;
656 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
657 if (!(VirtualBase= VirtualBase->getDefinition()))
658 continue;
660 return cloneFullComment(FC, D);
661 }
662 }
663 }
664 return nullptr;
665 }
666
667 // If the RawComment was attached to other redeclaration of this Decl, we
668 // should parse the comment in context of that other Decl. This is important
669 // because comments can contain references to parameter names which can be
670 // different across redeclarations.
671 if (D != OriginalDecl && OriginalDecl)
672 return getCommentForDecl(OriginalDecl, PP);
673
674 comments::FullComment *FC = RC->parse(*this, PP, D);
675 ParsedComments[Canonical] = FC;
676 return FC;
677}
678
679void ASTContext::CanonicalTemplateTemplateParm::Profile(
680 llvm::FoldingSetNodeID &ID, const ASTContext &C,
682 ID.AddInteger(Parm->getDepth());
683 ID.AddInteger(Parm->getPosition());
684 ID.AddBoolean(Parm->isParameterPack());
685 ID.AddInteger(Parm->templateParameterKind());
686
688 ID.AddInteger(Params->size());
690 PEnd = Params->end();
691 P != PEnd; ++P) {
692 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
693 ID.AddInteger(0);
694 ID.AddBoolean(TTP->isParameterPack());
695 ID.AddInteger(
696 TTP->getNumExpansionParameters().toInternalRepresentation());
697 continue;
698 }
699
700 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
701 ID.AddInteger(1);
702 ID.AddBoolean(NTTP->isParameterPack());
703 ID.AddPointer(C.getUnconstrainedType(C.getCanonicalType(NTTP->getType()))
704 .getAsOpaquePtr());
705 if (NTTP->isExpandedParameterPack()) {
706 ID.AddBoolean(true);
707 ID.AddInteger(NTTP->getNumExpansionTypes());
708 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
709 QualType T = NTTP->getExpansionType(I);
710 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
711 }
712 } else
713 ID.AddBoolean(false);
714 continue;
715 }
716
717 auto *TTP = cast<TemplateTemplateParmDecl>(*P);
718 ID.AddInteger(2);
719 Profile(ID, C, TTP);
720 }
721}
722
723TemplateTemplateParmDecl *
725 TemplateTemplateParmDecl *TTP) const {
726 // Check if we already have a canonical template template parameter.
727 llvm::FoldingSetNodeID ID;
728 CanonicalTemplateTemplateParm::Profile(ID, *this, TTP);
729 llvm::FoldingSetInsertToken Token;
730 CanonicalTemplateTemplateParm *Canonical =
731 CanonTemplateTemplateParms.lookup(ID, Token);
732 if (Canonical)
733 return Canonical->getParam();
734
735 // Build a canonical template parameter list.
737 SmallVector<NamedDecl *, 4> CanonParams;
738 CanonParams.reserve(Params->size());
740 PEnd = Params->end();
741 P != PEnd; ++P) {
742 // Note that, per C++20 [temp.over.link]/6, when determining whether
743 // template-parameters are equivalent, constraints are ignored.
744 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
747 TTP->getDepth(), TTP->getIndex(), nullptr, false,
748 TTP->isParameterPack(), /*HasTypeConstraint=*/false,
749 TTP->getNumExpansionParameters());
750 CanonParams.push_back(NewTTP);
751 } else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
755 if (NTTP->isExpandedParameterPack()) {
756 SmallVector<QualType, 2> ExpandedTypes;
758 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
759 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
760 ExpandedTInfos.push_back(
761 getTrivialTypeSourceInfo(ExpandedTypes.back()));
762 }
763
767 NTTP->getDepth(),
768 NTTP->getPosition(), nullptr,
769 T,
770 TInfo,
771 ExpandedTypes,
772 ExpandedTInfos);
773 } else {
777 NTTP->getDepth(),
778 NTTP->getPosition(), nullptr,
779 T,
780 NTTP->isParameterPack(),
781 TInfo);
782 }
783 CanonParams.push_back(Param);
784 } else
785 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
787 }
788
791 TTP->getPosition(), TTP->isParameterPack(), nullptr,
793 /*Typename=*/false,
795 CanonParams, SourceLocation(),
796 /*RequiresClause=*/nullptr));
797
798 // Get the new insert position for the node we care about.
799 Canonical = CanonTemplateTemplateParms.lookup(ID, Token);
800 assert(!Canonical && "Shouldn't be in the map!");
801 (void)Canonical;
802
803 // Create the canonical template template parameter entry.
804 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
805 CanonTemplateTemplateParms.insert(Canonical, Token);
806 return CanonTTP;
807}
808
811 TemplateTemplateParmDecl *TTP) const {
812 llvm::FoldingSetNodeID ID;
813 CanonicalTemplateTemplateParm::Profile(ID, *this, TTP);
814 llvm::FoldingSetInsertToken Token;
815 CanonicalTemplateTemplateParm *Canonical =
816 CanonTemplateTemplateParms.lookup(ID, Token);
817 return Canonical ? Canonical->getParam() : nullptr;
818}
819
822 TemplateTemplateParmDecl *CanonTTP) const {
823 llvm::FoldingSetNodeID ID;
824 CanonicalTemplateTemplateParm::Profile(ID, *this, CanonTTP);
825 llvm::FoldingSetInsertToken Token;
826 if (auto *Existing = CanonTemplateTemplateParms.lookup(ID, Token))
827 return Existing->getParam();
828 CanonTemplateTemplateParms.insert(
829 new (*this) CanonicalTemplateTemplateParm(CanonTTP), Token);
830 return CanonTTP;
831}
832
833/// For the purposes of overflow pattern exclusion, does this match the
834/// while(i--) pattern?
835static bool matchesPostDecrInWhile(const UnaryOperator *UO, ASTContext &Ctx) {
836 if (UO->getOpcode() != UO_PostDec)
837 return false;
838
839 if (!UO->getType()->isUnsignedIntegerType())
840 return false;
841
842 // -fsanitize-undefined-ignore-overflow-pattern=unsigned-post-decr-while
845 return false;
846
847 // all Parents (usually just one) must be a WhileStmt
848 return llvm::all_of(
850 [](const DynTypedNode &P) { return P.get<WhileStmt>() != nullptr; });
851}
852
854 // -fsanitize-undefined-ignore-overflow-pattern=negated-unsigned-const
855 // ... like -1UL;
856 if (UO->getOpcode() == UO_Minus &&
857 getLangOpts().isOverflowPatternExcluded(
859 UO->isIntegerConstantExpr(*this)) {
860 return true;
861 }
862
863 if (matchesPostDecrInWhile(UO, *this))
864 return true;
865
866 return false;
867}
868
869/// Check if a type can have its sanitizer instrumentation elided based on its
870/// presence within an ignorelist.
872 const QualType &Ty) const {
873 std::string TyName = Ty.getUnqualifiedType().getAsString(getPrintingPolicy());
874 return NoSanitizeL->containsType(Mask, TyName);
875}
876
878 auto Kind = getTargetInfo().getCXXABI().getKind();
879 return getLangOpts().CXXABI.value_or(Kind);
880}
881
882CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
883 if (!LangOpts.CPlusPlus) return nullptr;
884
885 switch (getCXXABIKind()) {
886 case TargetCXXABI::AppleARM64:
887 case TargetCXXABI::Fuchsia:
888 case TargetCXXABI::GenericARM: // Same as Itanium at this level
889 case TargetCXXABI::iOS:
890 case TargetCXXABI::WatchOS:
891 case TargetCXXABI::GenericAArch64:
892 case TargetCXXABI::GenericMIPS:
893 case TargetCXXABI::GenericItanium:
894 case TargetCXXABI::WebAssembly:
895 case TargetCXXABI::XL:
896 return CreateItaniumCXXABI(*this);
897 case TargetCXXABI::Microsoft:
898 return CreateMicrosoftCXXABI(*this);
899 }
900 llvm_unreachable("Invalid CXXABI type!");
901}
902
904 if (!InterpContext) {
905 InterpContext.reset(new interp::Context(const_cast<ASTContext &>(*this)));
906 }
907 return *InterpContext;
908}
909
911 if (!ParentMapCtx)
912 ParentMapCtx.reset(new ParentMapContext(*this));
913 return *ParentMapCtx;
914}
915
917 const LangOptions &LangOpts) {
918 switch (LangOpts.getAddressSpaceMapMangling()) {
920 return TI.useAddressSpaceMapMangling();
922 return true;
924 return false;
925 }
926 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
927}
928
930 IdentifierTable &idents, SelectorTable &sels,
932 : ConstantArrayTypes(this_(), ConstantArrayTypesLog2InitSize),
933 DependentSizedArrayTypes(this_()), DependentSizedExtVectorTypes(this_()),
934 DependentAddressSpaceTypes(this_()), DependentVectorTypes(this_()),
935 DependentSizedMatrixTypes(this_()),
936 FunctionProtoTypes(this_(), FunctionProtoTypesLog2InitSize),
937 DependentTypeOfExprTypes(this_()), DependentDecltypeTypes(this_()),
938 DependentPackIndexingTypes(this_()), TemplateSpecializationTypes(this_()),
939 AttributedTypes(this_()), DependentBitIntTypes(this_()),
940 HLSLAttributedResourceTypes(this_()),
941 SubstTemplateTemplateParmPacks(this_()), DeducedTemplates(this_()),
942 PackIndexingTemplates(this_()), ArrayParameterTypes(this_()),
943 CanonTemplateTemplateParms(this_()), SourceMgr(SM), LangOpts(LOpts),
944 NoSanitizeL(new NoSanitizeList(LangOpts.NoSanitizeFiles, SM)),
945 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
946 LangOpts.XRayNeverInstrumentFiles,
947 LangOpts.XRayAttrListFiles, SM)),
948 ProfList(new ProfileList(LangOpts.ProfileListFiles, SM)),
949 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
950 BuiltinInfo(builtins), TUKind(TUKind), DeclarationNames(*this),
951 Comments(SM), CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
952 CompCategories(this_()), LastSDM(nullptr, 0) {
954}
955
957 // Release the DenseMaps associated with DeclContext objects.
958 // FIXME: Is this the ideal solution?
959 ReleaseDeclContextMaps();
960
961 // Call all of the deallocation functions on all of their targets.
962 for (auto &Pair : Deallocations)
963 (Pair.first)(Pair.second);
964 Deallocations.clear();
965
966 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
967 // because they can contain DenseMaps.
968 for (llvm::DenseMap<const ObjCInterfaceDecl *,
970 I = ObjCLayouts.begin(),
971 E = ObjCLayouts.end();
972 I != E;)
973 // Increment in loop to prevent using deallocated memory.
974 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
975 R->Destroy(*this);
976 ObjCLayouts.clear();
977
978 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
979 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
980 // Increment in loop to prevent using deallocated memory.
981 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
982 R->Destroy(*this);
983 }
984 ASTRecordLayouts.clear();
985
986 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
987 AEnd = DeclAttrs.end();
988 A != AEnd; ++A)
989 A->second->~AttrVec();
990 DeclAttrs.clear();
991 LastDeclAttrsDecl = nullptr;
992
993 CtorClosureDefaultArgs.clear();
994
995 for (const auto &Value : ModuleInitializers)
996 Value.second->~PerModuleInitializers();
997 ModuleInitializers.clear();
998
999 TUDecl = nullptr;
1000 XRayFilter.reset();
1001 NoSanitizeL.reset();
1002}
1003
1005
1006void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
1007 TraversalScope = TopLevelDecls;
1009}
1010
1011void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const {
1012 Deallocations.push_back({Callback, Data});
1013}
1014
1015void
1019
1021 llvm::errs() << "\n*** AST Context Stats:\n";
1022 llvm::errs() << " " << Types.size() << " types total.\n";
1023
1024 unsigned counts[] = {
1025#define TYPE(Name, Parent) 0,
1026#define ABSTRACT_TYPE(Name, Parent)
1027#include "clang/AST/TypeNodes.inc"
1028 0 // Extra
1029 };
1030
1031 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
1032 Type *T = Types[i];
1033 counts[(unsigned)T->getTypeClass()]++;
1034 }
1035
1036 unsigned Idx = 0;
1037 unsigned TotalBytes = 0;
1038#define TYPE(Name, Parent) \
1039 if (counts[Idx]) \
1040 llvm::errs() << " " << counts[Idx] << " " << #Name \
1041 << " types, " << sizeof(Name##Type) << " each " \
1042 << "(" << counts[Idx] * sizeof(Name##Type) \
1043 << " bytes)\n"; \
1044 TotalBytes += counts[Idx] * sizeof(Name##Type); \
1045 ++Idx;
1046#define ABSTRACT_TYPE(Name, Parent)
1047#include "clang/AST/TypeNodes.inc"
1048
1049 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
1050
1051 // Implicit special member functions.
1052 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
1054 << " implicit default constructors created\n";
1055 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
1057 << " implicit copy constructors created\n";
1058 if (getLangOpts().CPlusPlus)
1059 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
1061 << " implicit move constructors created\n";
1062 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
1064 << " implicit copy assignment operators created\n";
1065 if (getLangOpts().CPlusPlus)
1066 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
1068 << " implicit move assignment operators created\n";
1069 llvm::errs() << NumImplicitDestructorsDeclared << "/"
1071 << " implicit destructors created\n";
1072
1073 if (ExternalSource) {
1074 llvm::errs() << "\n";
1075 ExternalSource->PrintStats();
1076 }
1077
1078 BumpAlloc.PrintStats();
1079}
1080
1082 bool NotifyListeners) {
1083 if (NotifyListeners)
1084 if (auto *Listener = getASTMutationListener();
1086 Listener->RedefinedHiddenDefinition(ND, M);
1087
1088 MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M);
1089}
1090
1092 auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl()));
1093 if (It == MergedDefModules.end())
1094 return;
1095
1096 auto &Merged = It->second;
1097 llvm::DenseSet<Module*> Found;
1098 for (Module *&M : Merged)
1099 if (!Found.insert(M).second)
1100 M = nullptr;
1101 llvm::erase(Merged, nullptr);
1102}
1103
1106 auto MergedIt =
1107 MergedDefModules.find(cast<NamedDecl>(Def->getCanonicalDecl()));
1108 if (MergedIt == MergedDefModules.end())
1109 return {};
1110 return MergedIt->second;
1111}
1112
1113void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
1114 if (LazyInitializers.empty())
1115 return;
1116
1117 auto *Source = Ctx.getExternalSource();
1118 assert(Source && "lazy initializers but no external source");
1119
1120 auto LazyInits = std::move(LazyInitializers);
1121 LazyInitializers.clear();
1122
1123 for (auto ID : LazyInits)
1124 Initializers.push_back(Source->GetExternalDecl(ID));
1125
1126 assert(LazyInitializers.empty() &&
1127 "GetExternalDecl for lazy module initializer added more inits");
1128}
1129
1131 // One special case: if we add a module initializer that imports another
1132 // module, and that module's only initializer is an ImportDecl, simplify.
1133 if (const auto *ID = dyn_cast<ImportDecl>(D)) {
1134 auto It = ModuleInitializers.find(ID->getImportedModule());
1135
1136 // Maybe the ImportDecl does nothing at all. (Common case.)
1137 if (It == ModuleInitializers.end())
1138 return;
1139
1140 // Maybe the ImportDecl only imports another ImportDecl.
1141 auto &Imported = *It->second;
1142 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
1143 Imported.resolve(*this);
1144 auto *OnlyDecl = Imported.Initializers.front();
1145 if (isa<ImportDecl>(OnlyDecl))
1146 D = OnlyDecl;
1147 }
1148 }
1149
1150 auto *&Inits = ModuleInitializers[M];
1151 if (!Inits)
1152 Inits = new (*this) PerModuleInitializers;
1153 Inits->Initializers.push_back(D);
1154}
1155
1158 auto *&Inits = ModuleInitializers[M];
1159 if (!Inits)
1160 Inits = new (*this) PerModuleInitializers;
1161 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
1162 IDs.begin(), IDs.end());
1163}
1164
1166 auto It = ModuleInitializers.find(M);
1167 if (It == ModuleInitializers.end())
1168 return {};
1169
1170 auto *Inits = It->second;
1171 Inits->resolve(*this);
1172 return Inits->Initializers;
1173}
1174
1176 assert(M->isNamedModule());
1177 assert(!CurrentCXXNamedModule &&
1178 "We should set named module for ASTContext for only once");
1179 CurrentCXXNamedModule = M;
1180}
1181
1182bool ASTContext::isInSameModule(const Module *M1, const Module *M2) const {
1183 if (!M1 != !M2)
1184 return false;
1185
1186 /// Get the representative module for M. The representative module is the
1187 /// first module unit for a specific primary module name. So that the module
1188 /// units have the same representative module belongs to the same module.
1189 ///
1190 /// The process is helpful to reduce the expensive string operations.
1191 auto GetRepresentativeModule = [this](const Module *M) {
1192 auto Iter = SameModuleLookupSet.find(M);
1193 if (Iter != SameModuleLookupSet.end())
1194 return Iter->second;
1195
1196 const Module *RepresentativeModule =
1197 PrimaryModuleNameMap.try_emplace(M->getPrimaryModuleInterfaceName(), M)
1198 .first->second;
1199 SameModuleLookupSet[M] = RepresentativeModule;
1200 return RepresentativeModule;
1201 };
1202
1203 assert(M1 && "Shouldn't call `isInSameModule` if both M1 and M2 are none.");
1204 return GetRepresentativeModule(M1) == GetRepresentativeModule(M2);
1205}
1206
1208 if (!ExternCContext)
1209 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1210
1211 return ExternCContext;
1212}
1213
1224
1225#define BuiltinTemplate(BTName) \
1226 BuiltinTemplateDecl *ASTContext::get##BTName##Decl() const { \
1227 if (!Decl##BTName) \
1228 Decl##BTName = \
1229 buildBuiltinTemplateDecl(BTK##BTName, get##BTName##Name()); \
1230 return Decl##BTName; \
1231 }
1232#include "clang/Basic/BuiltinTemplates.inc"
1233
1235 RecordDecl::TagKind TK) const {
1236 SourceLocation Loc;
1237 RecordDecl *NewDecl;
1238 if (getLangOpts().CPlusPlus)
1239 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1240 Loc, &Idents.get(Name));
1241 else
1242 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1243 &Idents.get(Name));
1244 NewDecl->setImplicit();
1245 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1246 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
1247 return NewDecl;
1248}
1249
1251 StringRef Name) const {
1254 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1255 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1256 NewDecl->setImplicit();
1257 return NewDecl;
1258}
1259
1261 if (!Int128Decl)
1262 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
1263 return Int128Decl;
1264}
1265
1267 if (!UInt128Decl)
1268 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
1269 return UInt128Decl;
1270}
1271
1272void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
1273 auto *Ty = new (*this, alignof(BuiltinType)) BuiltinType(K);
1275 Types.push_back(Ty);
1276}
1277
1279 const TargetInfo *AuxTarget) {
1280 assert((!this->Target || this->Target == &Target) &&
1281 "Incorrect target reinitialization");
1282 assert(VoidTy.isNull() && "Context reinitialized?");
1283
1284 this->Target = &Target;
1285 this->AuxTarget = AuxTarget;
1286
1287 ABI.reset(createCXXABI(Target));
1288 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
1289
1290 // C99 6.2.5p19.
1291 InitBuiltinType(VoidTy, BuiltinType::Void);
1292
1293 // C99 6.2.5p2.
1294 InitBuiltinType(BoolTy, BuiltinType::Bool);
1295 // C99 6.2.5p3.
1296 if (LangOpts.CharIsSigned)
1297 InitBuiltinType(CharTy, BuiltinType::Char_S);
1298 else
1299 InitBuiltinType(CharTy, BuiltinType::Char_U);
1300 // C99 6.2.5p4.
1301 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1302 InitBuiltinType(ShortTy, BuiltinType::Short);
1303 InitBuiltinType(IntTy, BuiltinType::Int);
1304 InitBuiltinType(LongTy, BuiltinType::Long);
1305 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
1306
1307 // C99 6.2.5p6.
1308 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1309 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1310 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1311 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1312 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
1313
1314 // C99 6.2.5p10.
1315 InitBuiltinType(FloatTy, BuiltinType::Float);
1316 InitBuiltinType(DoubleTy, BuiltinType::Double);
1317 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
1318
1319 // GNU extension, __float128 for IEEE quadruple precision
1320 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1321
1322 // __ibm128 for IBM extended precision
1323 InitBuiltinType(Ibm128Ty, BuiltinType::Ibm128);
1324
1325 // C11 extension ISO/IEC TS 18661-3
1326 InitBuiltinType(Float16Ty, BuiltinType::Float16);
1327
1328 // ISO/IEC JTC1 SC22 WG14 N1169 Extension
1329 InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum);
1330 InitBuiltinType(AccumTy, BuiltinType::Accum);
1331 InitBuiltinType(LongAccumTy, BuiltinType::LongAccum);
1332 InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum);
1333 InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum);
1334 InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum);
1335 InitBuiltinType(ShortFractTy, BuiltinType::ShortFract);
1336 InitBuiltinType(FractTy, BuiltinType::Fract);
1337 InitBuiltinType(LongFractTy, BuiltinType::LongFract);
1338 InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract);
1339 InitBuiltinType(UnsignedFractTy, BuiltinType::UFract);
1340 InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract);
1341 InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum);
1342 InitBuiltinType(SatAccumTy, BuiltinType::SatAccum);
1343 InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum);
1344 InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
1345 InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum);
1346 InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum);
1347 InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract);
1348 InitBuiltinType(SatFractTy, BuiltinType::SatFract);
1349 InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract);
1350 InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
1351 InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract);
1352 InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract);
1353
1354 // GNU extension, 128-bit integers.
1355 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1356 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1357
1358 // C++ 3.9.1p5
1359 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1360 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1361 else // -fshort-wchar makes wchar_t be unsigned.
1362 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1363 if (LangOpts.CPlusPlus && LangOpts.WChar)
1365 else {
1366 // C99 (or C++ using -fno-wchar).
1367 WideCharTy = getFromTargetType(Target.getWCharType());
1368 }
1369
1370 WIntTy = getFromTargetType(Target.getWIntType());
1371
1372 // C++20 (proposed)
1373 InitBuiltinType(Char8Ty, BuiltinType::Char8);
1374
1375 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1376 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1377 else // C99
1378 Char16Ty = getFromTargetType(Target.getChar16Type());
1379
1380 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1381 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1382 else // C99
1383 Char32Ty = getFromTargetType(Target.getChar32Type());
1384
1385 // Placeholder type for type-dependent expressions whose type is
1386 // completely unknown. No code should ever check a type against
1387 // DependentTy and users should never see it; however, it is here to
1388 // help diagnose failures to properly check for type-dependent
1389 // expressions.
1390 InitBuiltinType(DependentTy, BuiltinType::Dependent);
1391
1392 // Placeholder type for functions.
1393 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1394
1395 // Placeholder type for bound members.
1396 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1397
1398 // Placeholder type for unresolved templates.
1399 InitBuiltinType(UnresolvedTemplateTy, BuiltinType::UnresolvedTemplate);
1400
1401 // Placeholder type for pseudo-objects.
1402 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1403
1404 // "any" type; useful for debugger-like clients.
1405 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1406
1407 // Placeholder type for unbridged ARC casts.
1408 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1409
1410 // Placeholder type for builtin functions.
1411 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1412
1413 // Placeholder type for OMP array sections.
1414 if (LangOpts.OpenMP) {
1415 InitBuiltinType(ArraySectionTy, BuiltinType::ArraySection);
1416 InitBuiltinType(OMPArrayShapingTy, BuiltinType::OMPArrayShaping);
1417 InitBuiltinType(OMPIteratorTy, BuiltinType::OMPIterator);
1418 }
1419 // Placeholder type for OpenACC array sections, if we are ALSO in OMP mode,
1420 // don't bother, as we're just using the same type as OMP.
1421 if (LangOpts.OpenACC && !LangOpts.OpenMP) {
1422 InitBuiltinType(ArraySectionTy, BuiltinType::ArraySection);
1423 }
1424 if (LangOpts.MatrixTypes)
1425 InitBuiltinType(IncompleteMatrixIdxTy, BuiltinType::IncompleteMatrixIdx);
1426
1427 // Builtin types for 'id', 'Class', and 'SEL'.
1428 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1429 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
1430 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
1431
1432 if (LangOpts.OpenCL) {
1433#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1434 InitBuiltinType(SingletonId, BuiltinType::Id);
1435#include "clang/Basic/OpenCLImageTypes.def"
1436
1437 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
1438 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
1439 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1440 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1441 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
1442
1443#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1444 InitBuiltinType(Id##Ty, BuiltinType::Id);
1445#include "clang/Basic/OpenCLExtensionTypes.def"
1446 }
1447
1448 if (LangOpts.HLSL) {
1449#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
1450 InitBuiltinType(SingletonId, BuiltinType::Id);
1451#include "clang/Basic/HLSLIntangibleTypes.def"
1452 }
1453
1454 if (Target.hasAArch64ACLETypes() ||
1455 (AuxTarget && AuxTarget->hasAArch64ACLETypes())) {
1456#define SVE_TYPE(Name, Id, SingletonId) \
1457 InitBuiltinType(SingletonId, BuiltinType::Id);
1458#include "clang/Basic/AArch64ACLETypes.def"
1459 }
1460
1461 if (Target.getTriple().isPPC64()) {
1462#define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
1463 InitBuiltinType(Id##Ty, BuiltinType::Id);
1464#include "clang/Basic/PPCTypes.def"
1465#define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
1466 InitBuiltinType(Id##Ty, BuiltinType::Id);
1467#include "clang/Basic/PPCTypes.def"
1468 }
1469
1470 if (Target.hasRISCVVTypes()) {
1471#define RVV_TYPE(Name, Id, SingletonId) \
1472 InitBuiltinType(SingletonId, BuiltinType::Id);
1473#include "clang/Basic/RISCVVTypes.def"
1474 }
1475
1476 if (Target.getTriple().isWasm() && Target.hasFeature("reference-types")) {
1477#define WASM_TYPE(Name, Id, SingletonId) \
1478 InitBuiltinType(SingletonId, BuiltinType::Id);
1479#include "clang/Basic/WebAssemblyReferenceTypes.def"
1480 }
1481
1482 if (Target.hasAMDGPUTypes() || (AuxTarget && (AuxTarget->hasAMDGPUTypes()))) {
1483#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) \
1484 InitBuiltinType(SingletonId, BuiltinType::Id);
1485#include "clang/Basic/AMDGPUTypes.def"
1486 }
1487
1488 if (Target.getTriple().isSPIRV() ||
1489 (AuxTarget && AuxTarget->getTriple().isSPIRV())) {
1490#define SPIRV_TYPE(Name, Id, SingletonId) \
1491 InitBuiltinType(SingletonId, BuiltinType::Id);
1492#include "clang/Basic/SPIRVTypes.def"
1493 }
1494
1495 // Builtin type for __objc_yes and __objc_no
1496 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1498
1499 ObjCConstantStringType = QualType();
1500
1501 ObjCSuperType = QualType();
1502
1503 // void * type
1504 if (LangOpts.OpenCLGenericAddressSpace) {
1505 auto Q = VoidTy.getQualifiers();
1506 Q.setAddressSpace(LangAS::opencl_generic);
1508 getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
1509 } else {
1511 }
1512
1513 // nullptr type (C++0x 2.14.7)
1514 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
1515
1516 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1517 InitBuiltinType(HalfTy, BuiltinType::Half);
1518
1519 InitBuiltinType(BFloat16Ty, BuiltinType::BFloat16);
1520
1521 // Builtin type used to help define __builtin_va_list.
1522 VaListTagDecl = nullptr;
1523
1524 // MSVC predeclares struct _GUID, and we need it to create MSGuidDecls.
1525 if (LangOpts.MicrosoftExt || LangOpts.Borland) {
1528 }
1529}
1530
1532 return SourceMgr.getDiagnostics();
1533}
1534
1536 // 85% of lookups use the most recent D, so use a one-entry cache.
1537 if (LastDeclAttrsDecl == D) {
1538 assert(LastDeclAttrs != nullptr && LastDeclAttrs == DeclAttrs[D]);
1539 return *LastDeclAttrs;
1540 }
1541
1542 AttrVec *&Result = DeclAttrs[D];
1543 if (!Result) {
1544 void *Mem = Allocate(sizeof(AttrVec));
1545 Result = new (Mem) AttrVec;
1546 }
1547
1548 LastDeclAttrsDecl = D;
1549 LastDeclAttrs = Result;
1550 return *Result;
1551}
1552
1553/// Erase the attributes corresponding to the given declaration.
1555 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1556 if (Pos != DeclAttrs.end()) {
1557 Pos->second->~AttrVec();
1558 DeclAttrs.erase(Pos);
1559 }
1560 if (LastDeclAttrsDecl == D)
1561 LastDeclAttrsDecl = nullptr;
1562}
1563
1566 return CtorClosureDefaultArgs.lookup(CD);
1567}
1568
1571 assert(!CtorClosureDefaultArgs.contains(CD));
1572 CtorClosureDefaultArgs[CD] = Args;
1573}
1574
1577 auto It =
1578 ExplicitInstantiations.find(cast<NamedDecl>(Spec->getCanonicalDecl()));
1579 if (It != ExplicitInstantiations.end())
1580 return It->second;
1581 return {};
1582}
1583
1586 ExplicitInstantiations[cast<NamedDecl>(Spec->getCanonicalDecl())].push_back(
1587 EID);
1588}
1589
1590// FIXME: Remove ?
1593 assert(Var->isStaticDataMember() && "Not a static data member");
1595 .dyn_cast<MemberSpecializationInfo *>();
1596}
1597
1600 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1601 TemplateOrInstantiation.find(Var);
1602 if (Pos == TemplateOrInstantiation.end())
1603 return {};
1604
1605 return Pos->second;
1606}
1607
1608void
1611 SourceLocation PointOfInstantiation) {
1612 assert(Inst->isStaticDataMember() && "Not a static data member");
1613 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1615 Tmpl, TSK, PointOfInstantiation));
1616}
1617
1618void
1621 assert(!TemplateOrInstantiation[Inst] &&
1622 "Already noted what the variable was instantiated from");
1623 TemplateOrInstantiation[Inst] = TSI;
1624}
1625
1626NamedDecl *
1628 return InstantiatedFromUsingDecl.lookup(UUD);
1629}
1630
1631void
1633 assert((isa<UsingDecl>(Pattern) ||
1636 "pattern decl is not a using decl");
1637 assert((isa<UsingDecl>(Inst) ||
1640 "instantiation did not produce a using decl");
1641 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1642 InstantiatedFromUsingDecl[Inst] = Pattern;
1643}
1644
1647 return InstantiatedFromUsingEnumDecl.lookup(UUD);
1648}
1649
1651 UsingEnumDecl *Pattern) {
1652 assert(!InstantiatedFromUsingEnumDecl[Inst] && "pattern already exists");
1653 InstantiatedFromUsingEnumDecl[Inst] = Pattern;
1654}
1655
1658 return InstantiatedFromUsingShadowDecl.lookup(Inst);
1659}
1660
1661void
1663 UsingShadowDecl *Pattern) {
1664 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1665 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1666}
1667
1668FieldDecl *
1670 return InstantiatedFromUnnamedFieldDecl.lookup(Field);
1671}
1672
1674 FieldDecl *Tmpl) {
1675 assert((!Inst->getDeclName() || Inst->isPlaceholderVar(getLangOpts())) &&
1676 "Instantiated field decl is not unnamed");
1677 assert((!Inst->getDeclName() || Inst->isPlaceholderVar(getLangOpts())) &&
1678 "Template field decl is not unnamed");
1679 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1680 "Already noted what unnamed field was instantiated from");
1681
1682 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1683}
1684
1689
1694
1695unsigned
1697 auto Range = overridden_methods(Method);
1698 return Range.end() - Range.begin();
1699}
1700
1703 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1704 OverriddenMethods.find(Method->getCanonicalDecl());
1705 if (Pos == OverriddenMethods.end())
1706 return overridden_method_range(nullptr, nullptr);
1707 return overridden_method_range(Pos->second.begin(), Pos->second.end());
1708}
1709
1711 const CXXMethodDecl *Overridden) {
1712 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1713 OverriddenMethods[Method].push_back(Overridden);
1714}
1715
1717 const NamedDecl *D,
1718 SmallVectorImpl<const NamedDecl *> &Overridden) const {
1719 assert(D);
1720
1721 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1722 Overridden.append(overridden_methods_begin(CXXMethod),
1723 overridden_methods_end(CXXMethod));
1724 return;
1725 }
1726
1727 const auto *Method = dyn_cast<ObjCMethodDecl>(D);
1728 if (!Method)
1729 return;
1730
1732 Method->getOverriddenMethods(OverDecls);
1733 Overridden.append(OverDecls.begin(), OverDecls.end());
1734}
1735
1736std::optional<ASTContext::CXXRecordDeclRelocationInfo>
1738 assert(RD);
1739 CXXRecordDecl *D = RD->getDefinition();
1740 auto it = RelocatableClasses.find(D);
1741 if (it != RelocatableClasses.end())
1742 return it->getSecond();
1743 return std::nullopt;
1744}
1745
1748 assert(RD);
1749 CXXRecordDecl *D = RD->getDefinition();
1750 assert(RelocatableClasses.find(D) == RelocatableClasses.end());
1751 RelocatableClasses.insert({D, Info});
1752}
1753
1755 const ASTContext &Context, const CXXRecordDecl *Class) {
1756 if (!Class->isPolymorphic())
1757 return false;
1758 const CXXRecordDecl *BaseType = Context.baseForVTableAuthentication(Class);
1759 using AuthAttr = VTablePointerAuthenticationAttr;
1760 const AuthAttr *ExplicitAuth = BaseType->getAttr<AuthAttr>();
1761 if (!ExplicitAuth)
1762 return Context.getLangOpts().PointerAuthVTPtrAddressDiscrimination;
1763 AuthAttr::AddressDiscriminationMode AddressDiscrimination =
1764 ExplicitAuth->getAddressDiscrimination();
1765 if (AddressDiscrimination == AuthAttr::DefaultAddressDiscrimination)
1766 return Context.getLangOpts().PointerAuthVTPtrAddressDiscrimination;
1767 return AddressDiscrimination == AuthAttr::AddressDiscrimination;
1768}
1769
1770ASTContext::PointerAuthContent
1771ASTContext::findPointerAuthContent(QualType T) const {
1772 assert(isPointerAuthenticationAvailable());
1773
1774 T = T.getCanonicalType();
1775 if (T->isDependentType())
1776 return PointerAuthContent::None;
1777
1778 if (T.hasAddressDiscriminatedPointerAuth())
1779 return PointerAuthContent::AddressDiscriminatedData;
1780 const RecordDecl *RD = T->getAsRecordDecl();
1781 if (!RD)
1782 return PointerAuthContent::None;
1783
1784 if (RD->isInvalidDecl())
1785 return PointerAuthContent::None;
1786
1787 if (auto Existing = RecordContainsAddressDiscriminatedPointerAuth.find(RD);
1788 Existing != RecordContainsAddressDiscriminatedPointerAuth.end())
1789 return Existing->second;
1790
1791 PointerAuthContent Result = PointerAuthContent::None;
1792
1793 auto SaveResultAndReturn = [&]() -> PointerAuthContent {
1794 auto [ResultIter, DidAdd] =
1795 RecordContainsAddressDiscriminatedPointerAuth.try_emplace(RD, Result);
1796 (void)ResultIter;
1797 (void)DidAdd;
1798 assert(DidAdd);
1799 return Result;
1800 };
1801 auto ShouldContinueAfterUpdate = [&](PointerAuthContent NewResult) {
1802 static_assert(PointerAuthContent::None <
1803 PointerAuthContent::AddressDiscriminatedVTable);
1804 static_assert(PointerAuthContent::AddressDiscriminatedVTable <
1805 PointerAuthContent::AddressDiscriminatedData);
1806 if (NewResult > Result)
1807 Result = NewResult;
1808 return Result != PointerAuthContent::AddressDiscriminatedData;
1809 };
1810 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1812 !ShouldContinueAfterUpdate(
1813 PointerAuthContent::AddressDiscriminatedVTable))
1814 return SaveResultAndReturn();
1815 for (auto Base : CXXRD->bases()) {
1816 if (!ShouldContinueAfterUpdate(findPointerAuthContent(Base.getType())))
1817 return SaveResultAndReturn();
1818 }
1819 }
1820 for (auto *FieldDecl : RD->fields()) {
1821 if (!ShouldContinueAfterUpdate(
1822 findPointerAuthContent(FieldDecl->getType())))
1823 return SaveResultAndReturn();
1824 }
1825 return SaveResultAndReturn();
1826}
1827
1829 assert(!Import->getNextLocalImport() &&
1830 "Import declaration already in the chain");
1831 assert(!Import->isFromASTFile() && "Non-local import declaration");
1832 if (!FirstLocalImport) {
1833 FirstLocalImport = Import;
1834 LastLocalImport = Import;
1835 return;
1836 }
1837
1838 LastLocalImport->setNextLocalImport(Import);
1839 LastLocalImport = Import;
1840}
1841
1842//===----------------------------------------------------------------------===//
1843// Type Sizing and Analysis
1844//===----------------------------------------------------------------------===//
1845
1846/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1847/// scalar floating point type.
1848const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1849 switch (T->castAs<BuiltinType>()->getKind()) {
1850 default:
1851 llvm_unreachable("Not a floating point type!");
1852 case BuiltinType::BFloat16:
1853 return Target->getBFloat16Format();
1854 case BuiltinType::Float16:
1855 return Target->getHalfFormat();
1856 case BuiltinType::Half:
1857 return Target->getHalfFormat();
1858 case BuiltinType::Float: return Target->getFloatFormat();
1859 case BuiltinType::Double: return Target->getDoubleFormat();
1860 case BuiltinType::Ibm128:
1861 return Target->getIbm128Format();
1862 case BuiltinType::LongDouble:
1863 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1864 return AuxTarget->getLongDoubleFormat();
1865 return Target->getLongDoubleFormat();
1866 case BuiltinType::Float128:
1867 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1868 return AuxTarget->getFloat128Format();
1869 return Target->getFloat128Format();
1870 }
1871}
1872
1873CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1874 unsigned Align = Target->getCharWidth();
1875
1876 const unsigned AlignFromAttr = D->getMaxAlignment();
1877 if (AlignFromAttr)
1878 Align = AlignFromAttr;
1879
1880 // __attribute__((aligned)) can increase or decrease alignment
1881 // *except* on a struct or struct member, where it only increases
1882 // alignment unless 'packed' is also specified.
1883 //
1884 // It is an error for alignas to decrease alignment, so we can
1885 // ignore that possibility; Sema should diagnose it.
1886 bool UseAlignAttrOnly;
1887 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D))
1888 UseAlignAttrOnly =
1889 FD->hasAttr<PackedAttr>() || FD->getParent()->hasAttr<PackedAttr>();
1890 else
1891 UseAlignAttrOnly = AlignFromAttr != 0;
1892 // If we're using the align attribute only, just ignore everything
1893 // else about the declaration and its type.
1894 if (UseAlignAttrOnly) {
1895 // do nothing
1896 } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
1897 QualType T = VD->getType();
1898 if (const auto *RT = T->getAs<ReferenceType>()) {
1899 if (ForAlignof)
1900 T = RT->getPointeeType();
1901 else
1902 T = getPointerType(RT->getPointeeType());
1903 }
1904 QualType BaseT = getBaseElementType(T);
1905 if (T->isFunctionType())
1906 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1907 else if (!BaseT->isIncompleteType()) {
1908 // Adjust alignments of declarations with array type by the
1909 // large-array alignment on the target.
1910 if (const ArrayType *arrayType = getAsArrayType(T)) {
1911 unsigned MinWidth = Target->getLargeArrayMinWidth();
1912 if (!ForAlignof && MinWidth) {
1914 Align = std::max(Align, Target->getLargeArrayAlign());
1917 Align = std::max(Align, Target->getLargeArrayAlign());
1918 }
1919 }
1920 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1921 if (BaseT.getQualifiers().hasUnaligned())
1922 Align = Target->getCharWidth();
1923 }
1924
1925 // Ensure minimum alignment for global variables.
1926 if (const auto *VD = dyn_cast<VarDecl>(D))
1927 if (VD->hasGlobalStorage() && !ForAlignof) {
1928 uint64_t TypeSize =
1929 !BaseT->isIncompleteType() ? getTypeSize(T.getTypePtr()) : 0;
1930 Align = std::max(Align, getMinGlobalAlignOfVar(TypeSize, VD));
1931 }
1932
1933 // Fields can be subject to extra alignment constraints, like if
1934 // the field is packed, the struct is packed, or the struct has a
1935 // a max-field-alignment constraint (#pragma pack). So calculate
1936 // the actual alignment of the field within the struct, and then
1937 // (as we're expected to) constrain that by the alignment of the type.
1938 if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
1939 const RecordDecl *Parent = Field->getParent();
1940 // We can only produce a sensible answer if the record is valid.
1941 if (!Parent->isInvalidDecl()) {
1942 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
1943
1944 // Start with the record's overall alignment.
1945 unsigned FieldAlign = toBits(Layout.getAlignment());
1946
1947 // Use the GCD of that and the offset within the record.
1948 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1949 if (Offset > 0) {
1950 // Alignment is always a power of 2, so the GCD will be a power of 2,
1951 // which means we get to do this crazy thing instead of Euclid's.
1952 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1953 if (LowBitOfOffset < FieldAlign)
1954 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1955 }
1956
1957 Align = std::min(Align, FieldAlign);
1958 }
1959 }
1960 }
1961
1962 // Some targets have hard limitation on the maximum requestable alignment in
1963 // aligned attribute for static variables.
1964 const unsigned MaxAlignedAttr = getTargetInfo().getMaxAlignedAttribute();
1965 const auto *VD = dyn_cast<VarDecl>(D);
1966 if (MaxAlignedAttr && VD && VD->getStorageClass() == SC_Static)
1967 Align = std::min(Align, MaxAlignedAttr);
1968
1969 return toCharUnitsFromBits(Align);
1970}
1971
1973 return toCharUnitsFromBits(Target->getExnObjectAlignment());
1974}
1975
1976// getTypeInfoDataSizeInChars - Return the size of a type, in
1977// chars. If the type is a record, its data size is returned. This is
1978// the size of the memcpy that's performed when assigning this type
1979// using a trivial copy/move assignment operator.
1982
1983 // In C++, objects can sometimes be allocated into the tail padding
1984 // of a base-class subobject. We decide whether that's possible
1985 // during class layout, so here we can just trust the layout results.
1986 if (getLangOpts().CPlusPlus) {
1987 if (const auto *RD = T->getAsCXXRecordDecl(); RD && !RD->isInvalidDecl()) {
1988 const ASTRecordLayout &layout = getASTRecordLayout(RD);
1989 Info.Width = layout.getDataSize();
1990 }
1991 }
1992
1993 return Info;
1994}
1995
1996/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1997/// instead of in bits prevents overflowing the uint64_t for some large arrays.
2000 const ConstantArrayType *CAT) {
2001 TypeInfoChars EltInfo = Context.getTypeInfoInChars(CAT->getElementType());
2002 uint64_t Size = CAT->getZExtSize();
2003 assert((Size == 0 || static_cast<uint64_t>(EltInfo.Width.getQuantity()) <=
2004 (uint64_t)(-1)/Size) &&
2005 "Overflow in array type char size evaluation");
2006 uint64_t Width = EltInfo.Width.getQuantity() * Size;
2007 unsigned Align = EltInfo.Align.getQuantity();
2008 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
2009 Context.getTargetInfo().getPointerWidth(LangAS::Default) == 64)
2010 Width = llvm::alignTo(Width, Align);
2013 EltInfo.AlignRequirement);
2014}
2015
2017 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
2018 return getConstantArrayInfoInChars(*this, CAT);
2019 TypeInfo Info = getTypeInfo(T);
2022}
2023
2027
2029 // HLSL doesn't promote all small integer types to int, it
2030 // just uses the rank-based promotion rules for all types.
2031 if (getLangOpts().HLSL)
2032 return false;
2033
2034 if (const auto *BT = T->getAs<BuiltinType>())
2035 switch (BT->getKind()) {
2036 case BuiltinType::Bool:
2037 case BuiltinType::Char_S:
2038 case BuiltinType::Char_U:
2039 case BuiltinType::SChar:
2040 case BuiltinType::UChar:
2041 case BuiltinType::Short:
2042 case BuiltinType::UShort:
2043 case BuiltinType::WChar_S:
2044 case BuiltinType::WChar_U:
2045 case BuiltinType::Char8:
2046 case BuiltinType::Char16:
2047 case BuiltinType::Char32:
2048 return true;
2049 default:
2050 return false;
2051 }
2052
2053 // Enumerated types are promotable to their compatible integer types
2054 // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
2055 if (const auto *ED = T->getAsEnumDecl()) {
2056 if (T->isDependentType() || ED->getPromotionType().isNull() ||
2057 ED->isScoped())
2058 return false;
2059
2060 return true;
2061 }
2062
2063 // OverflowBehaviorTypes are promotable if their underlying type is promotable
2064 if (const auto *OBT = T->getAs<OverflowBehaviorType>()) {
2065 return isPromotableIntegerType(OBT->getUnderlyingType());
2066 }
2067
2068 return false;
2069}
2070
2074
2076 return isAlignmentRequired(T.getTypePtr());
2077}
2078
2080 bool NeedsPreferredAlignment) const {
2081 // An alignment on a typedef overrides anything else.
2082 if (const auto *TT = T->getAs<TypedefType>())
2083 if (unsigned Align = TT->getDecl()->getMaxAlignment())
2084 return Align;
2085
2086 // If we have an (array of) complete type, we're done.
2088 if (!T->isIncompleteType())
2089 return NeedsPreferredAlignment ? getPreferredTypeAlign(T) : getTypeAlign(T);
2090
2091 // If we had an array type, its element type might be a typedef
2092 // type with an alignment attribute.
2093 if (const auto *TT = T->getAs<TypedefType>())
2094 if (unsigned Align = TT->getDecl()->getMaxAlignment())
2095 return Align;
2096
2097 // Otherwise, see if the declaration of the type had an attribute.
2098 if (const auto *TD = T->getAsTagDecl())
2099 return TD->getMaxAlignment();
2100
2101 return 0;
2102}
2103
2105 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
2106 if (I != MemoizedTypeInfo.end())
2107 return I->second;
2108
2109 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
2110 TypeInfo TI = getTypeInfoImpl(T);
2111 MemoizedTypeInfo[T] = TI;
2112 return TI;
2113}
2114
2115/// getTypeInfoImpl - Return the size of the specified type, in bits. This
2116/// method does not work on incomplete types.
2117///
2118/// FIXME: Pointers into different addr spaces could have different sizes and
2119/// alignment requirements: getPointerInfo should take an AddrSpace, this
2120/// should take a QualType, &c.
2121TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
2122 uint64_t Width = 0;
2123 unsigned Align = 8;
2126 switch (T->getTypeClass()) {
2127#define TYPE(Class, Base)
2128#define ABSTRACT_TYPE(Class, Base)
2129#define NON_CANONICAL_TYPE(Class, Base)
2130#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2131#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
2132 case Type::Class: \
2133 assert(!T->isDependentType() && "should not see dependent types here"); \
2134 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
2135#include "clang/AST/TypeNodes.inc"
2136 llvm_unreachable("Should not see dependent types");
2137
2138 case Type::FunctionNoProto:
2139 case Type::FunctionProto:
2140 // GCC extension: alignof(function) = 32 bits
2141 Width = 0;
2142 Align = 32;
2143 break;
2144
2145 case Type::IncompleteArray:
2146 case Type::VariableArray:
2147 case Type::ConstantArray:
2148 case Type::ArrayParameter: {
2149 // Model non-constant sized arrays as size zero, but track the alignment.
2150 uint64_t Size = 0;
2151 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
2152 Size = CAT->getZExtSize();
2153
2154 TypeInfo EltInfo = getTypeInfo(cast<ArrayType>(T)->getElementType());
2155 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
2156 "Overflow in array type bit size evaluation");
2157 Width = EltInfo.Width * Size;
2158 Align = EltInfo.Align;
2159 AlignRequirement = EltInfo.AlignRequirement;
2160 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
2161 getTargetInfo().getPointerWidth(LangAS::Default) == 64)
2162 Width = llvm::alignTo(Width, Align);
2163 break;
2164 }
2165
2166 case Type::ExtVector:
2167 case Type::Vector: {
2168 const auto *VT = cast<VectorType>(T);
2169 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
2170 Width = VT->isPackedVectorBoolType(*this)
2171 ? VT->getNumElements()
2172 : EltInfo.Width * VT->getNumElements();
2173 // Enforce at least byte size and alignment.
2174 Width = std::max<unsigned>(8, Width);
2175 Align = std::max<unsigned>(
2176 8, Target->vectorsAreElementAligned() ? EltInfo.Width : Width);
2177
2178 // If the alignment is not a power of 2, round up to the next power of 2.
2179 // This happens for non-power-of-2 length vectors.
2180 if (Align & (Align-1)) {
2181 Align = llvm::bit_ceil(Align);
2182 Width = llvm::alignTo(Width, Align);
2183 }
2184 // Adjust the alignment based on the target max.
2185 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
2186 if (TargetVectorAlign && TargetVectorAlign < Align)
2187 Align = TargetVectorAlign;
2188 if (VT->getVectorKind() == VectorKind::SveFixedLengthData)
2189 // Adjust the alignment for fixed-length SVE vectors. This is important
2190 // for non-power-of-2 vector lengths.
2191 Align = 128;
2192 else if (VT->getVectorKind() == VectorKind::SveFixedLengthPredicate)
2193 // Adjust the alignment for fixed-length SVE predicates.
2194 Align = 16;
2195 else if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
2196 VT->getVectorKind() == VectorKind::RVVFixedLengthMask ||
2197 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_1 ||
2198 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_2 ||
2199 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_4)
2200 // Adjust the alignment for fixed-length RVV vectors.
2201 Align = std::min<unsigned>(64, Width);
2202 break;
2203 }
2204
2205 case Type::ConstantMatrix: {
2206 const auto *MT = cast<ConstantMatrixType>(T);
2207 TypeInfo ElementInfo = getTypeInfo(MT->getElementType());
2208 // The internal layout of a matrix value is implementation defined.
2209 // Initially be ABI compatible with arrays with respect to alignment and
2210 // size.
2211 Width = ElementInfo.Width * MT->getNumRows() * MT->getNumColumns();
2212 Align = ElementInfo.Align;
2213 break;
2214 }
2215
2216 case Type::Builtin:
2217 switch (cast<BuiltinType>(T)->getKind()) {
2218 default: llvm_unreachable("Unknown builtin type!");
2219 case BuiltinType::Void:
2220 // GCC extension: alignof(void) = 8 bits.
2221 Width = 0;
2222 Align = 8;
2223 break;
2224 case BuiltinType::Bool:
2225 Width = Target->getBoolWidth();
2226 Align = Target->getBoolAlign();
2227 break;
2228 case BuiltinType::Char_S:
2229 case BuiltinType::Char_U:
2230 case BuiltinType::UChar:
2231 case BuiltinType::SChar:
2232 case BuiltinType::Char8:
2233 Width = Target->getCharWidth();
2234 Align = Target->getCharAlign();
2235 break;
2236 case BuiltinType::WChar_S:
2237 case BuiltinType::WChar_U:
2238 Width = Target->getWCharWidth();
2239 Align = Target->getWCharAlign();
2240 break;
2241 case BuiltinType::Char16:
2242 Width = Target->getChar16Width();
2243 Align = Target->getChar16Align();
2244 break;
2245 case BuiltinType::Char32:
2246 Width = Target->getChar32Width();
2247 Align = Target->getChar32Align();
2248 break;
2249 case BuiltinType::UShort:
2250 case BuiltinType::Short:
2251 Width = Target->getShortWidth();
2252 Align = Target->getShortAlign();
2253 break;
2254 case BuiltinType::UInt:
2255 case BuiltinType::Int:
2256 Width = Target->getIntWidth();
2257 Align = Target->getIntAlign();
2258 break;
2259 case BuiltinType::ULong:
2260 case BuiltinType::Long:
2261 Width = Target->getLongWidth();
2262 Align = Target->getLongAlign();
2263 break;
2264 case BuiltinType::ULongLong:
2265 case BuiltinType::LongLong:
2266 Width = Target->getLongLongWidth();
2267 Align = Target->getLongLongAlign();
2268 break;
2269 case BuiltinType::Int128:
2270 case BuiltinType::UInt128:
2271 Width = 128;
2272 Align = Target->getInt128Align();
2273 break;
2274 case BuiltinType::ShortAccum:
2275 case BuiltinType::UShortAccum:
2276 case BuiltinType::SatShortAccum:
2277 case BuiltinType::SatUShortAccum:
2278 Width = Target->getShortAccumWidth();
2279 Align = Target->getShortAccumAlign();
2280 break;
2281 case BuiltinType::Accum:
2282 case BuiltinType::UAccum:
2283 case BuiltinType::SatAccum:
2284 case BuiltinType::SatUAccum:
2285 Width = Target->getAccumWidth();
2286 Align = Target->getAccumAlign();
2287 break;
2288 case BuiltinType::LongAccum:
2289 case BuiltinType::ULongAccum:
2290 case BuiltinType::SatLongAccum:
2291 case BuiltinType::SatULongAccum:
2292 Width = Target->getLongAccumWidth();
2293 Align = Target->getLongAccumAlign();
2294 break;
2295 case BuiltinType::ShortFract:
2296 case BuiltinType::UShortFract:
2297 case BuiltinType::SatShortFract:
2298 case BuiltinType::SatUShortFract:
2299 Width = Target->getShortFractWidth();
2300 Align = Target->getShortFractAlign();
2301 break;
2302 case BuiltinType::Fract:
2303 case BuiltinType::UFract:
2304 case BuiltinType::SatFract:
2305 case BuiltinType::SatUFract:
2306 Width = Target->getFractWidth();
2307 Align = Target->getFractAlign();
2308 break;
2309 case BuiltinType::LongFract:
2310 case BuiltinType::ULongFract:
2311 case BuiltinType::SatLongFract:
2312 case BuiltinType::SatULongFract:
2313 Width = Target->getLongFractWidth();
2314 Align = Target->getLongFractAlign();
2315 break;
2316 case BuiltinType::BFloat16:
2317 if (Target->hasBFloat16Type()) {
2318 Width = Target->getBFloat16Width();
2319 Align = Target->getBFloat16Align();
2320 } else if ((getLangOpts().SYCLIsDevice ||
2321 (getLangOpts().OpenMP &&
2322 getLangOpts().OpenMPIsTargetDevice)) &&
2323 AuxTarget->hasBFloat16Type()) {
2324 Width = AuxTarget->getBFloat16Width();
2325 Align = AuxTarget->getBFloat16Align();
2326 }
2327 break;
2328 case BuiltinType::Float16:
2329 case BuiltinType::Half:
2330 if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
2331 !getLangOpts().OpenMPIsTargetDevice) {
2332 Width = Target->getHalfWidth();
2333 Align = Target->getHalfAlign();
2334 } else {
2335 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2336 "Expected OpenMP device compilation.");
2337 Width = AuxTarget->getHalfWidth();
2338 Align = AuxTarget->getHalfAlign();
2339 }
2340 break;
2341 case BuiltinType::Float:
2342 Width = Target->getFloatWidth();
2343 Align = Target->getFloatAlign();
2344 break;
2345 case BuiltinType::Double:
2346 Width = Target->getDoubleWidth();
2347 Align = Target->getDoubleAlign();
2348 break;
2349 case BuiltinType::Ibm128:
2350 Width = Target->getIbm128Width();
2351 Align = Target->getIbm128Align();
2352 break;
2353 case BuiltinType::LongDouble:
2354 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2355 (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() ||
2356 Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) {
2357 Width = AuxTarget->getLongDoubleWidth();
2358 Align = AuxTarget->getLongDoubleAlign();
2359 } else {
2360 Width = Target->getLongDoubleWidth();
2361 Align = Target->getLongDoubleAlign();
2362 }
2363 break;
2364 case BuiltinType::Float128:
2365 if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
2366 !getLangOpts().OpenMPIsTargetDevice) {
2367 Width = Target->getFloat128Width();
2368 Align = Target->getFloat128Align();
2369 } else {
2370 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2371 "Expected OpenMP device compilation.");
2372 Width = AuxTarget->getFloat128Width();
2373 Align = AuxTarget->getFloat128Align();
2374 }
2375 break;
2376 case BuiltinType::NullPtr:
2377 // C++ 3.9.1p11: sizeof(nullptr_t) == sizeof(void*)
2378 Width = Target->getPointerWidth(LangAS::Default);
2379 Align = Target->getPointerAlign(LangAS::Default);
2380 break;
2381 case BuiltinType::ObjCId:
2382 case BuiltinType::ObjCClass:
2383 case BuiltinType::ObjCSel:
2384 Width = Target->getPointerWidth(LangAS::Default);
2385 Align = Target->getPointerAlign(LangAS::Default);
2386 break;
2387 case BuiltinType::OCLSampler:
2388 case BuiltinType::OCLEvent:
2389 case BuiltinType::OCLClkEvent:
2390 case BuiltinType::OCLQueue:
2391 case BuiltinType::OCLReserveID:
2392#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2393 case BuiltinType::Id:
2394#include "clang/Basic/OpenCLImageTypes.def"
2395#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2396 case BuiltinType::Id:
2397#include "clang/Basic/OpenCLExtensionTypes.def"
2398 AS = Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
2399 Width = Target->getPointerWidth(AS);
2400 Align = Target->getPointerAlign(AS);
2401 break;
2402 // The SVE types are effectively target-specific. The length of an
2403 // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple
2404 // of 128 bits. There is one predicate bit for each vector byte, so the
2405 // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits.
2406 //
2407 // Because the length is only known at runtime, we use a dummy value
2408 // of 0 for the static length. The alignment values are those defined
2409 // by the Procedure Call Standard for the Arm Architecture.
2410#define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId) \
2411 case BuiltinType::Id: \
2412 Width = 0; \
2413 Align = 128; \
2414 break;
2415#define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId) \
2416 case BuiltinType::Id: \
2417 Width = 0; \
2418 Align = 16; \
2419 break;
2420#define SVE_OPAQUE_TYPE(Name, MangledName, Id, SingletonId) \
2421 case BuiltinType::Id: \
2422 Width = 0; \
2423 Align = 16; \
2424 break;
2425#define SVE_SCALAR_TYPE(Name, MangledName, Id, SingletonId, Bits) \
2426 case BuiltinType::Id: \
2427 Width = Bits; \
2428 Align = Bits; \
2429 break;
2430#include "clang/Basic/AArch64ACLETypes.def"
2431#define PPC_VECTOR_TYPE(Name, Id, Size) \
2432 case BuiltinType::Id: \
2433 Width = Size; \
2434 Align = Size; \
2435 break;
2436#include "clang/Basic/PPCTypes.def"
2437#define RVV_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, NF, IsSigned, \
2438 IsFP, IsBF) \
2439 case BuiltinType::Id: \
2440 Width = 0; \
2441 Align = ElBits; \
2442 break;
2443#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, ElKind) \
2444 case BuiltinType::Id: \
2445 Width = 0; \
2446 Align = 8; \
2447 break;
2448#include "clang/Basic/RISCVVTypes.def"
2449#define WASM_TYPE(Name, Id, SingletonId) \
2450 case BuiltinType::Id: \
2451 Width = 0; \
2452 Align = 8; \
2453 break;
2454#include "clang/Basic/WebAssemblyReferenceTypes.def"
2455#define AMDGPU_TYPE(NAME, ID, SINGLETONID, WIDTH, ALIGN) \
2456 case BuiltinType::ID: \
2457 Width = WIDTH; \
2458 Align = ALIGN; \
2459 break;
2460#include "clang/Basic/AMDGPUTypes.def"
2461#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
2462#include "clang/Basic/HLSLIntangibleTypes.def"
2463 Width = Target->getPointerWidth(LangAS::Default);
2464 Align = Target->getPointerAlign(LangAS::Default);
2465 break;
2466#define SPIRV_TYPE(Name, Id, SingletonId) \
2467 case BuiltinType::Id: \
2468 Width = Target->getPointerWidth(LangAS::Default); \
2469 Align = Target->getPointerAlign(LangAS::Default); \
2470 break;
2471#include "clang/Basic/SPIRVTypes.def"
2472 }
2473 break;
2474 case Type::ObjCObjectPointer:
2475 Width = Target->getPointerWidth(LangAS::Default);
2476 Align = Target->getPointerAlign(LangAS::Default);
2477 break;
2478 case Type::BlockPointer:
2479 AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
2480 Width = Target->getPointerWidth(AS);
2481 Align = Target->getPointerAlign(AS);
2482 break;
2483 case Type::LValueReference:
2484 case Type::RValueReference:
2485 // alignof and sizeof should never enter this code path here, so we go
2486 // the pointer route.
2487 AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
2488 Width = Target->getPointerWidth(AS);
2489 Align = Target->getPointerAlign(AS);
2490 break;
2491 case Type::Pointer:
2492 AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
2493 Width = Target->getPointerWidth(AS);
2494 Align = Target->getPointerAlign(AS);
2495 break;
2496 case Type::MemberPointer: {
2497 const auto *MPT = cast<MemberPointerType>(T);
2498 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
2499 Width = MPI.Width;
2500 Align = MPI.Align;
2501 break;
2502 }
2503 case Type::Complex: {
2504 // Complex types have the same alignment as their elements, but twice the
2505 // size.
2506 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
2507 Width = EltInfo.Width * 2;
2508 Align = EltInfo.Align;
2509 break;
2510 }
2511 case Type::ObjCObject:
2512 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
2513 case Type::Adjusted:
2514 case Type::Decayed:
2515 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
2516 case Type::ObjCInterface: {
2517 const auto *ObjCI = cast<ObjCInterfaceType>(T);
2518 if (ObjCI->getDecl()->isInvalidDecl()) {
2519 Width = 8;
2520 Align = 8;
2521 break;
2522 }
2523 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2524 Width = toBits(Layout.getSize());
2525 Align = toBits(Layout.getAlignment());
2526 break;
2527 }
2528 case Type::BitInt: {
2529 const auto *EIT = cast<BitIntType>(T);
2530 Align = Target->getBitIntAlign(EIT->getNumBits());
2531 Width = Target->getBitIntWidth(EIT->getNumBits());
2532 break;
2533 }
2534 case Type::Record:
2535 case Type::Enum: {
2536 const auto *TT = cast<TagType>(T);
2537 const TagDecl *TD = TT->getDecl()->getDefinitionOrSelf();
2538
2539 if (TD->isInvalidDecl()) {
2540 Width = 8;
2541 Align = 8;
2542 break;
2543 }
2544
2545 if (isa<EnumType>(TT)) {
2546 const EnumDecl *ED = cast<EnumDecl>(TD);
2547 TypeInfo Info =
2549 if (unsigned AttrAlign = ED->getMaxAlignment()) {
2550 Info.Align = AttrAlign;
2552 }
2553 return Info;
2554 }
2555
2556 const auto *RD = cast<RecordDecl>(TD);
2557 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2558 Width = toBits(Layout.getSize());
2559 Align = toBits(Layout.getAlignment());
2560 AlignRequirement = RD->hasAttr<AlignedAttr>()
2562 : AlignRequirementKind::None;
2563 break;
2564 }
2565
2566 case Type::SubstTemplateTypeParm:
2568 getReplacementType().getTypePtr());
2569
2570 case Type::Auto:
2571 case Type::DeducedTemplateSpecialization: {
2572 const auto *A = cast<DeducedType>(T);
2573 assert(!A->getDeducedType().isNull() &&
2574 "cannot request the size of an undeduced or dependent auto type");
2575 return getTypeInfo(A->getDeducedType().getTypePtr());
2576 }
2577
2578 case Type::Paren:
2579 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
2580
2581 case Type::MacroQualified:
2582 return getTypeInfo(
2584
2585 case Type::ObjCTypeParam:
2586 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
2587
2588 case Type::Using:
2589 return getTypeInfo(cast<UsingType>(T)->desugar().getTypePtr());
2590
2591 case Type::Typedef: {
2592 const auto *TT = cast<TypedefType>(T);
2593 TypeInfo Info = getTypeInfo(TT->desugar().getTypePtr());
2594 // If the typedef has an aligned attribute on it, it overrides any computed
2595 // alignment we have. This violates the GCC documentation (which says that
2596 // attribute(aligned) can only round up) but matches its implementation.
2597 if (unsigned AttrAlign = TT->getDecl()->getMaxAlignment()) {
2598 Align = AttrAlign;
2599 AlignRequirement = AlignRequirementKind::RequiredByTypedef;
2600 } else {
2601 Align = Info.Align;
2602 AlignRequirement = Info.AlignRequirement;
2603 }
2604 Width = Info.Width;
2605 break;
2606 }
2607
2608 case Type::Attributed:
2609 return getTypeInfo(
2610 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
2611
2612 case Type::CountAttributed:
2613 return getTypeInfo(cast<CountAttributedType>(T)->desugar().getTypePtr());
2614
2615 case Type::LateParsedAttr:
2616 return getTypeInfo(cast<LateParsedAttrType>(T)->desugar().getTypePtr());
2617
2618 case Type::BTFTagAttributed:
2619 return getTypeInfo(
2620 cast<BTFTagAttributedType>(T)->getWrappedType().getTypePtr());
2621
2622 case Type::OverflowBehavior:
2623 return getTypeInfo(
2625
2626 case Type::HLSLAttributedResource:
2627 return getTypeInfo(
2628 cast<HLSLAttributedResourceType>(T)->getWrappedType().getTypePtr());
2629
2630 case Type::HLSLInlineSpirv: {
2631 const auto *ST = cast<HLSLInlineSpirvType>(T);
2632 // Size is specified in bytes, convert to bits
2633 Width = ST->getSize() * 8;
2634 Align = ST->getAlignment();
2635 if (Width == 0 && Align == 0) {
2636 // We are defaulting to laying out opaque SPIR-V types as 32-bit ints.
2637 Width = 32;
2638 Align = 32;
2639 }
2640 break;
2641 }
2642
2643 case Type::Atomic: {
2644 // Start with the base type information.
2645 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
2646 Width = Info.Width;
2647 Align = Info.Align;
2648
2649 if (!Width) {
2650 // An otherwise zero-sized type should still generate an
2651 // atomic operation.
2652 Width = Target->getCharWidth();
2653 assert(Align);
2654 } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2655 // If the size of the type doesn't exceed the platform's max
2656 // atomic promotion width, make the size and alignment more
2657 // favorable to atomic operations:
2658
2659 // Round the size up to a power of 2.
2660 Width = llvm::bit_ceil(Width);
2661
2662 // Set the alignment equal to the size.
2663 Align = static_cast<unsigned>(Width);
2664 }
2665 }
2666 break;
2667
2668 case Type::PredefinedSugar:
2669 return getTypeInfo(cast<PredefinedSugarType>(T)->desugar().getTypePtr());
2670
2671 case Type::Pipe:
2672 Width = Target->getPointerWidth(LangAS::opencl_global);
2673 Align = Target->getPointerAlign(LangAS::opencl_global);
2674 break;
2675 }
2676
2677 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
2678 return TypeInfo(Width, Align, AlignRequirement);
2679}
2680
2682 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
2683 if (I != MemoizedUnadjustedAlign.end())
2684 return I->second;
2685
2686 unsigned UnadjustedAlign;
2687 if (const auto *RT = T->getAsCanonical<RecordType>()) {
2688 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
2689 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2690 } else if (const auto *ObjCI = T->getAsCanonical<ObjCInterfaceType>()) {
2691 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2692 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2693 } else {
2694 UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType());
2695 }
2696
2697 MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2698 return UnadjustedAlign;
2699}
2700
2702 unsigned SimdAlign = llvm::OpenMPIRBuilder::getOpenMPDefaultSimdAlign(
2703 getTargetInfo().getTriple(), Target->getTargetOpts().FeatureMap);
2704 return SimdAlign;
2705}
2706
2707/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2709 return CharUnits::fromQuantity(BitSize / getCharWidth());
2710}
2711
2712/// toBits - Convert a size in characters to a size in characters.
2713int64_t ASTContext::toBits(CharUnits CharSize) const {
2714 return CharSize.getQuantity() * getCharWidth();
2715}
2716
2717/// getTypeSizeInChars - Return the size of the specified type, in characters.
2718/// This method does not work on incomplete types.
2725
2726/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
2727/// characters. This method does not work on incomplete types.
2734
2735/// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2736/// type, in characters, before alignment adjustments. This method does
2737/// not work on incomplete types.
2744
2745/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2746/// type for the current target in bits. This can be different than the ABI
2747/// alignment in cases where it is beneficial for performance or backwards
2748/// compatibility preserving to overalign a data type. (Note: despite the name,
2749/// the preferred alignment is ABI-impacting, and not an optimization.)
2751 TypeInfo TI = getTypeInfo(T);
2752 unsigned ABIAlign = TI.Align;
2753
2754 T = T->getBaseElementTypeUnsafe();
2755
2756 // The preferred alignment of member pointers is that of a pointer.
2757 if (T->isMemberPointerType())
2758 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2759
2760 if (!Target->allowsLargerPreferedTypeAlignment())
2761 return ABIAlign;
2762
2763 if (const auto *RD = T->getAsRecordDecl()) {
2764 // When used as part of a typedef, or together with a 'packed' attribute,
2765 // the 'aligned' attribute can be used to decrease alignment. Note that the
2766 // 'packed' case is already taken into consideration when computing the
2767 // alignment, we only need to handle the typedef case here.
2769 RD->isInvalidDecl())
2770 return ABIAlign;
2771
2772 unsigned PreferredAlign = static_cast<unsigned>(
2773 toBits(getASTRecordLayout(RD).PreferredAlignment));
2774 assert(PreferredAlign >= ABIAlign &&
2775 "PreferredAlign should be at least as large as ABIAlign.");
2776 return PreferredAlign;
2777 }
2778
2779 // Double (and, for targets supporting AIX `power` alignment, long double) and
2780 // long long should be naturally aligned (despite requiring less alignment) if
2781 // possible.
2782 if (const auto *CT = T->getAs<ComplexType>())
2783 T = CT->getElementType().getTypePtr();
2784 if (const auto *ED = T->getAsEnumDecl())
2785 T = ED->getIntegerType().getTypePtr();
2786 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
2787 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2788 T->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2789 (T->isSpecificBuiltinType(BuiltinType::LongDouble) &&
2790 Target->defaultsToAIXPowerAlignment()))
2791 // Don't increase the alignment if an alignment attribute was specified on a
2792 // typedef declaration.
2793 if (!TI.isAlignRequired())
2794 return std::max(ABIAlign, (unsigned)getTypeSize(T));
2795
2796 return ABIAlign;
2797}
2798
2799/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2800/// for __attribute__((aligned)) on this target, to be used if no alignment
2801/// value is specified.
2805
2806/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2807/// to a global variable of the specified type.
2809 uint64_t TypeSize = getTypeSize(T.getTypePtr());
2810 return std::max(getPreferredTypeAlign(T),
2811 getMinGlobalAlignOfVar(TypeSize, VD));
2812}
2813
2814/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2815/// should be given to a global variable of the specified type.
2820
2822 const VarDecl *VD) const {
2823 // Make the default handling as that of a non-weak definition in the
2824 // current translation unit.
2825 bool HasNonWeakDef = !VD || (VD->hasDefinition() && !VD->isWeak());
2826 return getTargetInfo().getMinGlobalAlign(Size, HasNonWeakDef);
2827}
2828
2830 CharUnits Offset = CharUnits::Zero();
2831 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2832 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2833 Offset += Layout->getBaseClassOffset(Base);
2834 Layout = &getASTRecordLayout(Base);
2835 }
2836 return Offset;
2837}
2838
2840 const ValueDecl *MPD = MP.getMemberPointerDecl();
2843 bool DerivedMember = MP.isMemberPointerToDerivedMember();
2845 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
2846 const CXXRecordDecl *Base = RD;
2847 const CXXRecordDecl *Derived = Path[I];
2848 if (DerivedMember)
2849 std::swap(Base, Derived);
2851 RD = Path[I];
2852 }
2853 if (DerivedMember)
2855 return ThisAdjustment;
2856}
2857
2858/// DeepCollectObjCIvars -
2859/// This routine first collects all declared, but not synthesized, ivars in
2860/// super class and then collects all ivars, including those synthesized for
2861/// current class. This routine is used for implementation of current class
2862/// when all ivars, declared and synthesized are known.
2864 bool leafClass,
2866 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2867 DeepCollectObjCIvars(SuperClass, false, Ivars);
2868 if (!leafClass) {
2869 llvm::append_range(Ivars, OI->ivars());
2870 } else {
2871 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
2872 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
2873 Iv= Iv->getNextIvar())
2874 Ivars.push_back(Iv);
2875 }
2876}
2877
2878/// CollectInheritedProtocols - Collect all protocols in current class and
2879/// those inherited by it.
2882 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2883 // We can use protocol_iterator here instead of
2884 // all_referenced_protocol_iterator since we are walking all categories.
2885 for (auto *Proto : OI->all_referenced_protocols()) {
2886 CollectInheritedProtocols(Proto, Protocols);
2887 }
2888
2889 // Categories of this Interface.
2890 for (const auto *Cat : OI->visible_categories())
2891 CollectInheritedProtocols(Cat, Protocols);
2892
2893 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2894 while (SD) {
2895 CollectInheritedProtocols(SD, Protocols);
2896 SD = SD->getSuperClass();
2897 }
2898 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
2899 for (auto *Proto : OC->protocols()) {
2900 CollectInheritedProtocols(Proto, Protocols);
2901 }
2902 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
2903 // Insert the protocol.
2904 if (!Protocols.insert(
2905 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2906 return;
2907
2908 for (auto *Proto : OP->protocols())
2909 CollectInheritedProtocols(Proto, Protocols);
2910 }
2911}
2912
2914 const RecordDecl *RD,
2915 bool CheckIfTriviallyCopyable) {
2916 assert(RD->isUnion() && "Must be union type");
2917 CharUnits UnionSize =
2918 Context.getTypeSizeInChars(Context.getCanonicalTagType(RD));
2919
2920 for (const auto *Field : RD->fields()) {
2921 if (!Context.hasUniqueObjectRepresentations(Field->getType(),
2922 CheckIfTriviallyCopyable))
2923 return false;
2924 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2925 if (FieldSize != UnionSize)
2926 return false;
2927 }
2928 return !RD->field_empty();
2929}
2930
2931static int64_t getSubobjectOffset(const FieldDecl *Field,
2932 const ASTContext &Context,
2933 const clang::ASTRecordLayout & /*Layout*/) {
2934 return Context.getFieldOffset(Field);
2935}
2936
2937static int64_t getSubobjectOffset(const CXXRecordDecl *RD,
2938 const ASTContext &Context,
2939 const clang::ASTRecordLayout &Layout) {
2940 return Context.toBits(Layout.getBaseClassOffset(RD));
2941}
2942
2943static std::optional<int64_t>
2945 const RecordDecl *RD,
2946 bool CheckIfTriviallyCopyable);
2947
2948static std::optional<int64_t>
2949getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context,
2950 bool CheckIfTriviallyCopyable) {
2951 if (const auto *RD = Field->getType()->getAsRecordDecl();
2952 RD && !RD->isUnion())
2953 return structHasUniqueObjectRepresentations(Context, RD,
2954 CheckIfTriviallyCopyable);
2955
2956 // A _BitInt type may not be unique if it has padding bits
2957 // but if it is a bitfield the padding bits are not used.
2958 bool IsBitIntType = Field->getType()->isBitIntType();
2959 if (!Field->getType()->isReferenceType() && !IsBitIntType &&
2960 !Context.hasUniqueObjectRepresentations(Field->getType(),
2961 CheckIfTriviallyCopyable))
2962 return std::nullopt;
2963
2964 int64_t FieldSizeInBits =
2965 Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2966 if (Field->isBitField()) {
2967 // If we have explicit padding bits, they don't contribute bits
2968 // to the actual object representation, so return 0.
2969 if (Field->isUnnamedBitField())
2970 return 0;
2971
2972 int64_t BitfieldSize = Field->getBitWidthValue();
2973 if (IsBitIntType) {
2974 if ((unsigned)BitfieldSize >
2975 cast<BitIntType>(Field->getType())->getNumBits())
2976 return std::nullopt;
2977 } else if (BitfieldSize > FieldSizeInBits) {
2978 return std::nullopt;
2979 }
2980 FieldSizeInBits = BitfieldSize;
2981 } else if (IsBitIntType && !Context.hasUniqueObjectRepresentations(
2982 Field->getType(), CheckIfTriviallyCopyable)) {
2983 return std::nullopt;
2984 }
2985 return FieldSizeInBits;
2986}
2987
2988static std::optional<int64_t>
2990 bool CheckIfTriviallyCopyable) {
2991 return structHasUniqueObjectRepresentations(Context, RD,
2992 CheckIfTriviallyCopyable);
2993}
2994
2995template <typename RangeT>
2997 const RangeT &Subobjects, int64_t CurOffsetInBits,
2998 const ASTContext &Context, const clang::ASTRecordLayout &Layout,
2999 bool CheckIfTriviallyCopyable) {
3000 for (const auto *Subobject : Subobjects) {
3001 std::optional<int64_t> SizeInBits =
3002 getSubobjectSizeInBits(Subobject, Context, CheckIfTriviallyCopyable);
3003 if (!SizeInBits)
3004 return std::nullopt;
3005 if (*SizeInBits != 0) {
3006 int64_t Offset = getSubobjectOffset(Subobject, Context, Layout);
3007 if (Offset != CurOffsetInBits)
3008 return std::nullopt;
3009 CurOffsetInBits += *SizeInBits;
3010 }
3011 }
3012 return CurOffsetInBits;
3013}
3014
3015static std::optional<int64_t>
3017 const RecordDecl *RD,
3018 bool CheckIfTriviallyCopyable) {
3019 assert(!RD->isUnion() && "Must be struct/class type");
3020 const auto &Layout = Context.getASTRecordLayout(RD);
3021
3022 int64_t CurOffsetInBits = 0;
3023 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
3024 if (ClassDecl->isDynamicClass())
3025 return std::nullopt;
3026
3028 for (const auto &Base : ClassDecl->bases()) {
3029 // Empty types can be inherited from, and non-empty types can potentially
3030 // have tail padding, so just make sure there isn't an error.
3031 Bases.emplace_back(Base.getType()->getAsCXXRecordDecl());
3032 }
3033
3034 llvm::sort(Bases, [&](const CXXRecordDecl *L, const CXXRecordDecl *R) {
3035 return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R);
3036 });
3037
3038 std::optional<int64_t> OffsetAfterBases =
3040 Bases, CurOffsetInBits, Context, Layout, CheckIfTriviallyCopyable);
3041 if (!OffsetAfterBases)
3042 return std::nullopt;
3043 CurOffsetInBits = *OffsetAfterBases;
3044 }
3045
3046 std::optional<int64_t> OffsetAfterFields =
3048 RD->fields(), CurOffsetInBits, Context, Layout,
3049 CheckIfTriviallyCopyable);
3050 if (!OffsetAfterFields)
3051 return std::nullopt;
3052 CurOffsetInBits = *OffsetAfterFields;
3053
3054 return CurOffsetInBits;
3055}
3056
3058 QualType Ty, bool CheckIfTriviallyCopyable) const {
3059 // C++17 [meta.unary.prop]:
3060 // The predicate condition for a template specialization
3061 // has_unique_object_representations<T> shall be satisfied if and only if:
3062 // (9.1) - T is trivially copyable, and
3063 // (9.2) - any two objects of type T with the same value have the same
3064 // object representation, where:
3065 // - two objects of array or non-union class type are considered to have
3066 // the same value if their respective sequences of direct subobjects
3067 // have the same values, and
3068 // - two objects of union type are considered to have the same value if
3069 // they have the same active member and the corresponding members have
3070 // the same value.
3071 // The set of scalar types for which this condition holds is
3072 // implementation-defined. [ Note: If a type has padding bits, the condition
3073 // does not hold; otherwise, the condition holds true for unsigned integral
3074 // types. -- end note ]
3075 assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
3076
3077 // Arrays are unique only if their element type is unique.
3078 if (Ty->isArrayType())
3080 CheckIfTriviallyCopyable);
3081
3082 assert((Ty->isVoidType() || !Ty->isIncompleteType()) &&
3083 "hasUniqueObjectRepresentations should not be called with an "
3084 "incomplete type");
3085
3086 // (9.1) - T is trivially copyable...
3087 if (CheckIfTriviallyCopyable && !Ty.isTriviallyCopyableType(*this))
3088 return false;
3089
3090 // All integrals and enums are unique.
3091 if (Ty->isIntegralOrEnumerationType()) {
3092 // Address discriminated integer types are not unique.
3094 return false;
3095 // Except _BitInt types that have padding bits.
3096 if (const auto *BIT = Ty->getAs<BitIntType>())
3097 return getTypeSize(BIT) == BIT->getNumBits();
3098
3099 return true;
3100 }
3101
3102 // All other pointers are unique.
3103 if (Ty->isPointerType())
3105
3106 if (const auto *MPT = Ty->getAs<MemberPointerType>())
3107 return !ABI->getMemberPointerInfo(MPT).HasPadding;
3108
3109 if (const auto *Record = Ty->getAsRecordDecl()) {
3110 if (Record->isInvalidDecl())
3111 return false;
3112
3113 if (Record->isUnion())
3115 CheckIfTriviallyCopyable);
3116
3117 std::optional<int64_t> StructSize = structHasUniqueObjectRepresentations(
3118 *this, Record, CheckIfTriviallyCopyable);
3119
3120 return StructSize && *StructSize == static_cast<int64_t>(getTypeSize(Ty));
3121 }
3122
3123 // FIXME: More cases to handle here (list by rsmith):
3124 // vectors (careful about, eg, vector of 3 foo)
3125 // _Complex int and friends
3126 // _Atomic T
3127 // Obj-C block pointers
3128 // Obj-C object pointers
3129 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
3130 // clk_event_t, queue_t, reserve_id_t)
3131 // There're also Obj-C class types and the Obj-C selector type, but I think it
3132 // makes sense for those to return false here.
3133
3134 return false;
3135}
3136
3138 unsigned count = 0;
3139 // Count ivars declared in class extension.
3140 for (const auto *Ext : OI->known_extensions())
3141 count += Ext->ivar_size();
3142
3143 // Count ivar defined in this class's implementation. This
3144 // includes synthesized ivars.
3145 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
3146 count += ImplDecl->ivar_size();
3147
3148 return count;
3149}
3150
3152 if (!E)
3153 return false;
3154
3155 // nullptr_t is always treated as null.
3156 if (E->getType()->isNullPtrType()) return true;
3157
3158 if (E->getType()->isAnyPointerType() &&
3161 return true;
3162
3163 // Unfortunately, __null has type 'int'.
3164 if (isa<GNUNullExpr>(E)) return true;
3165
3166 return false;
3167}
3168
3169/// Get the implementation of ObjCInterfaceDecl, or nullptr if none
3170/// exists.
3172 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
3173 I = ObjCImpls.find(D);
3174 if (I != ObjCImpls.end())
3175 return cast<ObjCImplementationDecl>(I->second);
3176 return nullptr;
3177}
3178
3179/// Get the implementation of ObjCCategoryDecl, or nullptr if none
3180/// exists.
3182 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
3183 I = ObjCImpls.find(D);
3184 if (I != ObjCImpls.end())
3185 return cast<ObjCCategoryImplDecl>(I->second);
3186 return nullptr;
3187}
3188
3189/// Set the implementation of ObjCInterfaceDecl.
3191 ObjCImplementationDecl *ImplD) {
3192 assert(IFaceD && ImplD && "Passed null params");
3193 ObjCImpls[IFaceD] = ImplD;
3194}
3195
3196/// Set the implementation of ObjCCategoryDecl.
3198 ObjCCategoryImplDecl *ImplD) {
3199 assert(CatD && ImplD && "Passed null params");
3200 ObjCImpls[CatD] = ImplD;
3201}
3202
3203const ObjCMethodDecl *
3205 return ObjCMethodRedecls.lookup(MD);
3206}
3207
3209 const ObjCMethodDecl *Redecl) {
3210 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
3211 ObjCMethodRedecls[MD] = Redecl;
3212}
3213
3215 const NamedDecl *ND) const {
3216 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
3217 return ID;
3218 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
3219 return CD->getClassInterface();
3220 if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
3221 return IMD->getClassInterface();
3222
3223 return nullptr;
3224}
3225
3226/// Get the copy initialization expression of VarDecl, or nullptr if
3227/// none exists.
3229 assert(VD && "Passed null params");
3230 assert(VD->hasAttr<BlocksAttr>() &&
3231 "getBlockVarCopyInits - not __block var");
3232 auto I = BlockVarCopyInits.find(VD);
3233 if (I != BlockVarCopyInits.end())
3234 return I->second;
3235 return {nullptr, false};
3236}
3237
3238/// Set the copy initialization expression of a block var decl.
3240 bool CanThrow) {
3241 assert(VD && CopyExpr && "Passed null params");
3242 assert(VD->hasAttr<BlocksAttr>() &&
3243 "setBlockVarCopyInits - not __block var");
3244 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
3245}
3246
3248 unsigned DataSize) const {
3249 if (!DataSize)
3251 else
3252 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
3253 "incorrect data size provided to CreateTypeSourceInfo!");
3254
3255 auto *TInfo =
3256 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
3257 new (TInfo) TypeSourceInfo(T, DataSize);
3258 return TInfo;
3259}
3260
3262 SourceLocation L) const {
3264 TSI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
3265 return TSI;
3266}
3267
3268const ASTRecordLayout &
3270 return getObjCLayout(D);
3271}
3272
3275 bool &AnyNonCanonArgs) {
3276 SmallVector<TemplateArgument, 16> CanonArgs(Args);
3277 AnyNonCanonArgs |= C.canonicalizeTemplateArguments(CanonArgs);
3278 return CanonArgs;
3279}
3280
3283 bool AnyNonCanonArgs = false;
3284 for (auto &Arg : Args) {
3285 TemplateArgument OrigArg = Arg;
3287 AnyNonCanonArgs |= !Arg.structurallyEquals(OrigArg);
3288 }
3289 return AnyNonCanonArgs;
3290}
3291
3292//===----------------------------------------------------------------------===//
3293// Type creation/memoization methods
3294//===----------------------------------------------------------------------===//
3295
3297ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
3298 unsigned fastQuals = quals.getFastQualifiers();
3299 quals.removeFastQualifiers();
3300
3301 // Check if we've already instantiated this type.
3302 llvm::FoldingSetNodeID ID;
3303 ExtQuals::Profile(ID, baseType, quals);
3304 llvm::FoldingSetInsertToken Token;
3305 if (ExtQuals *eq = ExtQualNodes.lookup(ID, Token)) {
3306 assert(eq->getQualifiers() == quals);
3307 return QualType(eq, fastQuals);
3308 }
3309
3310 // If the base type is not canonical, make the appropriate canonical type.
3311 QualType canon;
3312 if (!baseType->isCanonicalUnqualified()) {
3313 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
3314 canonSplit.Quals.addConsistentQualifiers(quals);
3315 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
3316
3317 // Re-find the insert position.
3318 (void)ExtQualNodes.lookup(ID, Token);
3319 }
3320
3321 auto *eq = new (*this, alignof(ExtQuals)) ExtQuals(baseType, canon, quals);
3322 ExtQualNodes.insert(eq, Token);
3323 return QualType(eq, fastQuals);
3324}
3325
3327 LangAS AddressSpace) const {
3328 QualType CanT = getCanonicalType(T);
3329 if (CanT.getAddressSpace() == AddressSpace)
3330 return T;
3331
3332 // If we are composing extended qualifiers together, merge together
3333 // into one ExtQuals node.
3334 QualifierCollector Quals;
3335 const Type *TypeNode = Quals.strip(T);
3336
3337 // If this type already has an address space specified, it cannot get
3338 // another one.
3339 assert(!Quals.hasAddressSpace() &&
3340 "Type cannot be in multiple addr spaces!");
3341 Quals.addAddressSpace(AddressSpace);
3342
3343 return getExtQualType(TypeNode, Quals);
3344}
3345
3347 // If the type is not qualified with an address space, just return it
3348 // immediately.
3349 if (!T.hasAddressSpace())
3350 return T;
3351
3352 QualifierCollector Quals;
3353 const Type *TypeNode;
3354 // For arrays, strip the qualifier off the element type, then reconstruct the
3355 // array type
3356 if (T.getTypePtr()->isArrayType()) {
3357 T = getUnqualifiedArrayType(T, Quals);
3358 TypeNode = T.getTypePtr();
3359 } else {
3360 // If we are composing extended qualifiers together, merge together
3361 // into one ExtQuals node.
3362 while (T.hasAddressSpace()) {
3363 TypeNode = Quals.strip(T);
3364
3365 // If the type no longer has an address space after stripping qualifiers,
3366 // jump out.
3367 if (!QualType(TypeNode, 0).hasAddressSpace())
3368 break;
3369
3370 // There might be sugar in the way. Strip it and try again.
3371 T = T.getSingleStepDesugaredType(*this);
3372 }
3373 }
3374
3375 Quals.removeAddressSpace();
3376
3377 // Removal of the address space can mean there are no longer any
3378 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
3379 // or required.
3380 if (Quals.hasNonFastQualifiers())
3381 return getExtQualType(TypeNode, Quals);
3382 else
3383 return QualType(TypeNode, Quals.getFastQualifiers());
3384}
3385
3386uint16_t
3388 bool IsVTTEntry) {
3389 assert(RD->isPolymorphic() &&
3390 "Attempted to get vtable pointer discriminator on a monomorphic type");
3391
3392 std::unique_ptr<MangleContext> MC(createMangleContext());
3393 SmallString<256> Str;
3394 llvm::raw_svector_ostream Out(Str);
3395 MC->mangleCXXVTable(RD, Out);
3396 if (IsVTTEntry)
3398 return llvm::getPointerAuthStableSipHash(Str);
3399}
3400
3401/// Encode a function type for use in the discriminator of a function pointer
3402/// type. We can't use the itanium scheme for this since C has quite permissive
3403/// rules for type compatibility that we need to be compatible with.
3404///
3405/// Formally, this function associates every function pointer type T with an
3406/// encoded string E(T). Let the equivalence relation T1 ~ T2 be defined as
3407/// E(T1) == E(T2). E(T) is part of the ABI of values of type T. C type
3408/// compatibility requires equivalent treatment under the ABI, so
3409/// CCompatible(T1, T2) must imply E(T1) == E(T2), that is, CCompatible must be
3410/// a subset of ~. Crucially, however, it must be a proper subset because
3411/// CCompatible is not an equivalence relation: for example, int[] is compatible
3412/// with both int[1] and int[2], but the latter are not compatible with each
3413/// other. Therefore this encoding function must be careful to only distinguish
3414/// types if there is no third type with which they are both required to be
3415/// compatible.
3417 raw_ostream &OS, QualType QT) {
3418 // FIXME: Consider address space qualifiers.
3419 const Type *T = QT.getCanonicalType().getTypePtr();
3420
3421 // FIXME: Consider using the C++ type mangling when we encounter a construct
3422 // that is incompatible with C.
3423
3424 switch (T->getTypeClass()) {
3425 case Type::Atomic:
3427 Ctx, OS, cast<AtomicType>(T)->getValueType());
3428
3429 case Type::LValueReference:
3430 OS << "R";
3433 return;
3434 case Type::RValueReference:
3435 OS << "O";
3438 return;
3439
3440 case Type::Pointer:
3441 // C11 6.7.6.1p2:
3442 // For two pointer types to be compatible, both shall be identically
3443 // qualified and both shall be pointers to compatible types.
3444 // FIXME: we should also consider pointee types.
3445 OS << "P";
3446 return;
3447
3448 case Type::ObjCObjectPointer:
3449 case Type::BlockPointer:
3450 OS << "P";
3451 return;
3452
3453 case Type::Complex:
3454 OS << "C";
3456 Ctx, OS, cast<ComplexType>(T)->getElementType());
3457
3458 case Type::VariableArray:
3459 case Type::ConstantArray:
3460 case Type::IncompleteArray:
3461 case Type::ArrayParameter:
3462 // C11 6.7.6.2p6:
3463 // For two array types to be compatible, both shall have compatible
3464 // element types, and if both size specifiers are present, and are integer
3465 // constant expressions, then both size specifiers shall have the same
3466 // constant value [...]
3467 //
3468 // So since ElemType[N] has to be compatible ElemType[], we can't encode the
3469 // width of the array.
3470 OS << "A";
3472 Ctx, OS, cast<ArrayType>(T)->getElementType());
3473
3474 case Type::ObjCInterface:
3475 case Type::ObjCObject:
3476 OS << "<objc_object>";
3477 return;
3478
3479 case Type::Enum: {
3480 // C11 6.7.2.2p4:
3481 // Each enumerated type shall be compatible with char, a signed integer
3482 // type, or an unsigned integer type.
3483 //
3484 // So we have to treat enum types as integers.
3485 QualType UnderlyingType = T->castAsEnumDecl()->getIntegerType();
3487 Ctx, OS, UnderlyingType.isNull() ? Ctx.IntTy : UnderlyingType);
3488 }
3489
3490 case Type::FunctionNoProto:
3491 case Type::FunctionProto: {
3492 // C11 6.7.6.3p15:
3493 // For two function types to be compatible, both shall specify compatible
3494 // return types. Moreover, the parameter type lists, if both are present,
3495 // shall agree in the number of parameters and in the use of the ellipsis
3496 // terminator; corresponding parameters shall have compatible types.
3497 //
3498 // That paragraph goes on to describe how unprototyped functions are to be
3499 // handled, which we ignore here. Unprototyped function pointers are hashed
3500 // as though they were prototyped nullary functions since thats probably
3501 // what the user meant. This behavior is non-conforming.
3502 // FIXME: If we add a "custom discriminator" function type attribute we
3503 // should encode functions as their discriminators.
3504 OS << "F";
3505 const auto *FuncType = cast<FunctionType>(T);
3506 encodeTypeForFunctionPointerAuth(Ctx, OS, FuncType->getReturnType());
3507 if (const auto *FPT = dyn_cast<FunctionProtoType>(FuncType)) {
3508 for (QualType Param : FPT->param_types()) {
3509 Param = Ctx.getSignatureParameterType(Param);
3510 encodeTypeForFunctionPointerAuth(Ctx, OS, Param);
3511 }
3512 if (FPT->isVariadic())
3513 OS << "z";
3514 }
3515 OS << "E";
3516 return;
3517 }
3518
3519 case Type::MemberPointer: {
3520 OS << "M";
3521 const auto *MPT = T->castAs<MemberPointerType>();
3523 Ctx, OS, QualType(MPT->getQualifier().getAsType(), 0));
3524 encodeTypeForFunctionPointerAuth(Ctx, OS, MPT->getPointeeType());
3525 return;
3526 }
3527 case Type::ExtVector:
3528 case Type::Vector:
3529 OS << "Dv" << Ctx.getTypeSizeInChars(T).getQuantity();
3530 break;
3531
3532 // Don't bother discriminating based on these types.
3533 case Type::Pipe:
3534 case Type::BitInt:
3535 case Type::ConstantMatrix:
3536 OS << "?";
3537 return;
3538
3539 case Type::Builtin: {
3540 const auto *BTy = T->castAs<BuiltinType>();
3541 switch (BTy->getKind()) {
3542#define SIGNED_TYPE(Id, SingletonId) \
3543 case BuiltinType::Id: \
3544 OS << "i"; \
3545 return;
3546#define UNSIGNED_TYPE(Id, SingletonId) \
3547 case BuiltinType::Id: \
3548 OS << "i"; \
3549 return;
3550#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
3551#define BUILTIN_TYPE(Id, SingletonId)
3552#include "clang/AST/BuiltinTypes.def"
3553 llvm_unreachable("placeholder types should not appear here.");
3554
3555 case BuiltinType::Half:
3556 OS << "Dh";
3557 return;
3558 case BuiltinType::Float:
3559 OS << "f";
3560 return;
3561 case BuiltinType::Double:
3562 OS << "d";
3563 return;
3564 case BuiltinType::LongDouble:
3565 OS << "e";
3566 return;
3567 case BuiltinType::Float16:
3568 OS << "DF16_";
3569 return;
3570 case BuiltinType::Float128:
3571 OS << "g";
3572 return;
3573
3574 case BuiltinType::Void:
3575 OS << "v";
3576 return;
3577
3578 case BuiltinType::ObjCId:
3579 case BuiltinType::ObjCClass:
3580 case BuiltinType::ObjCSel:
3581 case BuiltinType::NullPtr:
3582 OS << "P";
3583 return;
3584
3585 // Don't bother discriminating based on OpenCL types.
3586 case BuiltinType::OCLSampler:
3587 case BuiltinType::OCLEvent:
3588 case BuiltinType::OCLClkEvent:
3589 case BuiltinType::OCLQueue:
3590 case BuiltinType::OCLReserveID:
3591 case BuiltinType::BFloat16:
3592 case BuiltinType::VectorQuad:
3593 case BuiltinType::VectorPair:
3594 case BuiltinType::DMR1024:
3595 case BuiltinType::DMR2048:
3596 OS << "?";
3597 return;
3598
3599 // Don't bother discriminating based on these seldom-used types.
3600 case BuiltinType::Ibm128:
3601 return;
3602#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
3603 case BuiltinType::Id: \
3604 return;
3605#include "clang/Basic/OpenCLImageTypes.def"
3606#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
3607 case BuiltinType::Id: \
3608 return;
3609#include "clang/Basic/OpenCLExtensionTypes.def"
3610#define SVE_TYPE(Name, Id, SingletonId) \
3611 case BuiltinType::Id: \
3612 return;
3613#include "clang/Basic/AArch64ACLETypes.def"
3614#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
3615 case BuiltinType::Id: \
3616 return;
3617#include "clang/Basic/HLSLIntangibleTypes.def"
3618 case BuiltinType::Dependent:
3619 llvm_unreachable("should never get here");
3620#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
3621#include "clang/Basic/AMDGPUTypes.def"
3622 case BuiltinType::WasmExternRef:
3623#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
3624#include "clang/Basic/RISCVVTypes.def"
3625#define SPIRV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
3626#include "clang/Basic/SPIRVTypes.def"
3627 llvm_unreachable("not yet implemented");
3628 }
3629 llvm_unreachable("should never get here");
3630 }
3631 case Type::Record: {
3632 const RecordDecl *RD = T->castAsCanonical<RecordType>()->getDecl();
3633 const IdentifierInfo *II = RD->getIdentifier();
3634
3635 // In C++, an immediate typedef of an anonymous struct or union
3636 // is considered to name it for ODR purposes, but C's specification
3637 // of type compatibility does not have a similar rule. Using the typedef
3638 // name in function type discriminators anyway, as we do here,
3639 // therefore technically violates the C standard: two function pointer
3640 // types defined in terms of two typedef'd anonymous structs with
3641 // different names are formally still compatible, but we are assigning
3642 // them different discriminators and therefore incompatible ABIs.
3643 //
3644 // This is a relatively minor violation that significantly improves
3645 // discrimination in some cases and has not caused problems in
3646 // practice. Regardless, it is now part of the ABI in places where
3647 // function type discrimination is used, and it can no longer be
3648 // changed except on new platforms.
3649
3650 if (!II)
3651 if (const TypedefNameDecl *Typedef = RD->getTypedefNameForAnonDecl())
3652 II = Typedef->getDeclName().getAsIdentifierInfo();
3653
3654 if (!II) {
3655 OS << "<anonymous_record>";
3656 return;
3657 }
3658 OS << II->getLength() << II->getName();
3659 return;
3660 }
3661 case Type::HLSLAttributedResource:
3662 case Type::HLSLInlineSpirv:
3663 llvm_unreachable("should never get here");
3664 break;
3665 case Type::OverflowBehavior:
3666 llvm_unreachable("should never get here");
3667 break;
3668 case Type::DeducedTemplateSpecialization:
3669 case Type::Auto:
3670#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3671#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3672#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3673#define ABSTRACT_TYPE(Class, Base)
3674#define TYPE(Class, Base)
3675#include "clang/AST/TypeNodes.inc"
3676 llvm_unreachable("unexpected non-canonical or dependent type!");
3677 return;
3678 }
3679}
3680
3682 assert(!T->isDependentType() &&
3683 "cannot compute type discriminator of a dependent type");
3684 SmallString<256> Str;
3685 llvm::raw_svector_ostream Out(Str);
3686
3687 if (T->isFunctionPointerType() || T->isFunctionReferenceType())
3688 T = T->getPointeeType();
3689
3690 if (T->isFunctionType()) {
3692 } else {
3693 T = T.getUnqualifiedType();
3694 // Calls to member function pointers don't need to worry about
3695 // language interop or the laxness of the C type compatibility rules.
3696 // We just mangle the member pointer type directly, which is
3697 // implicitly much stricter about type matching. However, we do
3698 // strip any top-level exception specification before this mangling.
3699 // C++23 requires calls to work when the function type is convertible
3700 // to the pointer type by a function pointer conversion, which can
3701 // change the exception specification. This does not technically
3702 // require the exception specification to not affect representation,
3703 // because the function pointer conversion is still always a direct
3704 // value conversion and therefore an opportunity to resign the
3705 // pointer. (This is in contrast to e.g. qualification conversions,
3706 // which can be applied in nested pointer positions, effectively
3707 // requiring qualified and unqualified representations to match.)
3708 // However, it is pragmatic to ignore exception specifications
3709 // because it allows a certain amount of `noexcept` mismatching
3710 // to not become a visible ODR problem. This also leaves some
3711 // room for the committee to add laxness to function pointer
3712 // conversions in future standards.
3713 if (auto *MPT = T->getAs<MemberPointerType>())
3714 if (MPT->isMemberFunctionPointer()) {
3715 QualType PointeeType = MPT->getPointeeType();
3716 if (PointeeType->castAs<FunctionProtoType>()->getExceptionSpecType() !=
3717 EST_None) {
3719 T = getMemberPointerType(FT, MPT->getQualifier(),
3720 MPT->getMostRecentCXXRecordDecl());
3721 }
3722 }
3723 std::unique_ptr<MangleContext> MC(createMangleContext());
3724 MC->mangleCanonicalTypeName(T, Out);
3725 }
3726
3727 return llvm::getPointerAuthStableSipHash(Str);
3728}
3729
3731 Qualifiers::GC GCAttr) const {
3732 QualType CanT = getCanonicalType(T);
3733 if (CanT.getObjCGCAttr() == GCAttr)
3734 return T;
3735
3736 if (const auto *ptr = T->getAs<PointerType>()) {
3737 QualType Pointee = ptr->getPointeeType();
3738 if (Pointee->isAnyPointerType()) {
3739 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
3740 return getPointerType(ResultType);
3741 }
3742 }
3743
3744 // If we are composing extended qualifiers together, merge together
3745 // into one ExtQuals node.
3746 QualifierCollector Quals;
3747 const Type *TypeNode = Quals.strip(T);
3748
3749 // If this type already has an ObjCGC specified, it cannot get
3750 // another one.
3751 assert(!Quals.hasObjCGCAttr() &&
3752 "Type cannot have multiple ObjCGCs!");
3753 Quals.addObjCGCAttr(GCAttr);
3754
3755 return getExtQualType(TypeNode, Quals);
3756}
3757
3759 if (const PointerType *Ptr = T->getAs<PointerType>()) {
3760 QualType Pointee = Ptr->getPointeeType();
3761 if (isPtrSizeAddressSpace(Pointee.getAddressSpace())) {
3762 return getPointerType(removeAddrSpaceQualType(Pointee));
3763 }
3764 }
3765 return T;
3766}
3767
3769 QualType WrappedTy, Expr *CountExpr, bool CountInBytes, bool OrNull,
3770 ArrayRef<TypeCoupledDeclRefInfo> DependentDecls) const {
3771 assert(WrappedTy->isPointerType() || WrappedTy->isArrayType());
3772 assert(CountExpr && "use getIncompleteCountAttributedType for a null count");
3773
3774 // Complete (non-late-parsed) path: the count expression is known up front.
3775 // This deliberately preserves the pre-existing uniquing behavior -- the
3776 // FoldingSet lookup/insert below is unchanged by late-parse support. Only
3777 // getIncompleteCountAttributedType (count filled in later) opts out of
3778 // uniquing.
3779 llvm::FoldingSetNodeID ID;
3780 CountAttributedType::Profile(ID, WrappedTy, CountExpr, CountInBytes, OrNull);
3781
3782 llvm::FoldingSetInsertToken Token;
3783 CountAttributedType *CATy = CountAttributedTypes.lookup(ID, Token);
3784 if (CATy)
3785 return QualType(CATy, 0);
3786
3787 QualType CanonTy = getCanonicalType(WrappedTy);
3788 CATy = CountAttributedType::Create(*this, WrappedTy, CanonTy, CountExpr,
3789 CountInBytes, OrNull, DependentDecls);
3790 Types.push_back(CATy);
3791 CountAttributedTypes.insert(CATy, Token);
3792
3793 return QualType(CATy, 0);
3794}
3795
3797 QualType WrappedTy, bool CountInBytes, bool OrNull) const {
3798 assert(WrappedTy->isPointerType() || WrappedTy->isArrayType());
3799
3800 // Deliberately opts out of the uniquing that `getCountAttributedType` does:
3801 // `CountAttributedType::Profile` keys on the `CountExpr` pointer, which is
3802 // null here, so every incomplete node would profile identically as
3803 // `(WrappedTy, flags, nullptr)` and two fields with different counts would
3804 // collide. The node stays un-uniqued even after completion; see
3805 // `completeCountAttributedType`.
3806 //
3807 // Also deliberately not in `Types` yet. An incomplete node can be abandoned
3808 // without ever being completed (a nested counted_by, or an argument that
3809 // fails to parse), and a null-count node must not be reachable by anything
3810 // that scans `Types`. `completeCountAttributedType` registers it once the
3811 // count is in place.
3812 return CountAttributedType::Create(
3813 *this, WrappedTy, getCanonicalType(WrappedTy),
3814 /*CountExpr=*/nullptr, CountInBytes, OrNull,
3815 /*CoupledDecls=*/{});
3816}
3817
3819 CountAttributedType *CATy, Expr *CountExpr,
3820 ArrayRef<TypeCoupledDeclRefInfo> DependentDecls) const {
3821 CATy->complete(*this, CountExpr, DependentDecls);
3822 // Safe for `Types` scanners now that the count is in place; see
3823 // `getIncompleteCountAttributedType` for why it was held back.
3824 //
3825 // It stays out of the `CountAttributedTypes` FoldingSet permanently, unlike
3826 // an eagerly built node: this pointer is already embedded in the enclosing
3827 // types and handed out, so an equal node that happens to exist cannot be
3828 // merged into. The only cost is that a completed node is never
3829 // pointer-shared with an equal eager one, which does not affect semantic
3830 // type equality -- `hasSameType` compares canonical types, and this sugar's
3831 // canonical type is the wrapped type's.
3832 Types.push_back(CATy);
3833}
3834
3836 QualType WrappedTy, LateParsedTypeAttribute *LateParsedAttr) const {
3837 QualType CanonTy = getCanonicalType(WrappedTy);
3838
3839 auto *LPATy = new (*this, alignof(LateParsedAttrType))
3840 LateParsedAttrType(WrappedTy, CanonTy, LateParsedAttr);
3841
3842 Types.push_back(LPATy);
3843 return QualType(LPATy, 0);
3844}
3845
3848 llvm::function_ref<QualType(QualType)> Adjust) const {
3849 switch (Orig->getTypeClass()) {
3850 case Type::Attributed: {
3851 const auto *AT = cast<AttributedType>(Orig);
3852 return getAttributedType(AT->getAttrKind(),
3853 adjustType(AT->getModifiedType(), Adjust),
3854 adjustType(AT->getEquivalentType(), Adjust),
3855 AT->getAttr());
3856 }
3857
3858 case Type::BTFTagAttributed: {
3859 const auto *BTFT = dyn_cast<BTFTagAttributedType>(Orig);
3860 return getBTFTagAttributedType(BTFT->getAttr(),
3861 adjustType(BTFT->getWrappedType(), Adjust));
3862 }
3863
3864 case Type::OverflowBehavior: {
3865 const auto *OB = dyn_cast<OverflowBehaviorType>(Orig);
3866 return getOverflowBehaviorType(OB->getBehaviorKind(),
3867 adjustType(OB->getUnderlyingType(), Adjust));
3868 }
3869
3870 case Type::Paren:
3871 return getParenType(
3872 adjustType(cast<ParenType>(Orig)->getInnerType(), Adjust));
3873
3874 case Type::Adjusted: {
3875 const auto *AT = cast<AdjustedType>(Orig);
3876 return getAdjustedType(AT->getOriginalType(),
3877 adjustType(AT->getAdjustedType(), Adjust));
3878 }
3879
3880 case Type::MacroQualified: {
3881 const auto *MQT = cast<MacroQualifiedType>(Orig);
3882 return getMacroQualifiedType(adjustType(MQT->getUnderlyingType(), Adjust),
3883 MQT->getMacroIdentifier());
3884 }
3885
3886 default:
3887 return Adjust(Orig);
3888 }
3889}
3890
3892 FunctionType::ExtInfo Info) {
3893 if (T->getExtInfo() == Info)
3894 return T;
3895
3897 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
3898 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
3899 } else {
3900 const auto *FPT = cast<FunctionProtoType>(T);
3901 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
3902 EPI.ExtInfo = Info;
3903 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
3904 }
3905
3906 return cast<FunctionType>(Result.getTypePtr());
3907}
3908
3910 QualType ResultType) {
3911 return adjustType(FunctionType, [&](QualType Orig) {
3912 if (const auto *FNPT = Orig->getAs<FunctionNoProtoType>())
3913 return getFunctionNoProtoType(ResultType, FNPT->getExtInfo());
3914
3915 const auto *FPT = Orig->castAs<FunctionProtoType>();
3916 return getFunctionType(ResultType, FPT->getParamTypes(),
3917 FPT->getExtProtoInfo());
3918 });
3919}
3920
3922 QualType ResultType) {
3923 FD = FD->getMostRecentDecl();
3924 while (true) {
3925 FD->setType(adjustFunctionResultType(FD->getType(), ResultType));
3926 if (FunctionDecl *Next = FD->getPreviousDecl())
3927 FD = Next;
3928 else
3929 break;
3930 }
3932 L->DeducedReturnType(FD, ResultType);
3933}
3934
3935/// Get a function type and produce the equivalent function type with the
3936/// specified exception specification. Type sugar that can be present on a
3937/// declaration of a function with an exception specification is permitted
3938/// and preserved. Other type sugar (for instance, typedefs) is not.
3940 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const {
3941 return adjustType(Orig, [&](QualType Ty) {
3942 const auto *Proto = Ty->castAs<FunctionProtoType>();
3943 return getFunctionType(Proto->getReturnType(), Proto->getParamTypes(),
3944 Proto->getExtProtoInfo().withExceptionSpec(ESI));
3945 });
3946}
3947
3955
3957 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3958 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3959 SmallVector<QualType, 16> Args(Proto->param_types().size());
3960 for (unsigned i = 0, n = Args.size(); i != n; ++i)
3961 Args[i] = removePtrSizeAddrSpace(Proto->param_types()[i]);
3962 return getFunctionType(RetTy, Args, Proto->getExtProtoInfo());
3963 }
3964
3965 if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) {
3966 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3967 return getFunctionNoProtoType(RetTy, Proto->getExtInfo());
3968 }
3969
3970 return T;
3971}
3972
3978
3980 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3981 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3982 EPI.ExtParameterInfos = nullptr;
3983 return getFunctionType(Proto->getReturnType(), Proto->param_types(), EPI);
3984 }
3985 return T;
3986}
3987
3993
3996 bool AsWritten) {
3997 // Update the type.
3998 QualType Updated =
4000 FD->setType(Updated);
4001
4002 if (!AsWritten)
4003 return;
4004
4005 // Update the type in the type source information too.
4006 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
4007 // If the type and the type-as-written differ, we may need to update
4008 // the type-as-written too.
4009 if (TSInfo->getType() != FD->getType())
4010 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
4011
4012 // FIXME: When we get proper type location information for exceptions,
4013 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
4014 // up the TypeSourceInfo;
4015 assert(TypeLoc::getFullDataSizeForType(Updated) ==
4016 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
4017 "TypeLoc size mismatch from updating exception specification");
4018 TSInfo->overrideType(Updated);
4019 }
4020}
4021
4022/// getComplexType - Return the uniqued reference to the type for a complex
4023/// number with the specified element type.
4025 // Unique pointers, to guarantee there is only one pointer of a particular
4026 // structure.
4027 llvm::FoldingSetInsertToken Token;
4028 if (ComplexType *CT = ComplexTypes.lookup(T, Token))
4029 return QualType(CT, 0);
4030
4031 // If the pointee type isn't canonical, this won't be a canonical type either,
4032 // so fill in the canonical type field.
4033 QualType Canonical;
4034 if (!T.isCanonical()) {
4035 Canonical = getComplexType(getCanonicalType(T));
4036
4037 assert(!ComplexTypes.lookup(T, Token) && "Shouldn't be in the map!");
4038 }
4039 auto *New = new (*this, alignof(ComplexType)) ComplexType(T, Canonical);
4040 Types.push_back(New);
4041 ComplexTypes.insert(New, Token);
4042 return QualType(New, 0);
4043}
4044
4045/// getPointerType - Return the uniqued reference to the type for a pointer to
4046/// the specified type.
4048 // Unique pointers, to guarantee there is only one pointer of a particular
4049 // structure.
4050 llvm::FoldingSetInsertToken Token;
4051 if (PointerType *PT = PointerTypes.lookup(T, Token))
4052 return QualType(PT, 0);
4053
4054 // If the pointee type isn't canonical, this won't be a canonical type either,
4055 // so fill in the canonical type field.
4056 QualType Canonical;
4057 if (!T.isCanonical()) {
4058 Canonical = getPointerType(getCanonicalType(T));
4059
4060 assert(!PointerTypes.lookup(T, Token) && "Shouldn't be in the map!");
4061 }
4062 auto *New = new (*this, alignof(PointerType)) PointerType(T, Canonical);
4063 Types.push_back(New);
4064 PointerTypes.insert(New, Token);
4065 return QualType(New, 0);
4066}
4067
4069 llvm::FoldingSetInsertToken Token;
4070 AdjustedType *AT = AdjustedTypes.lookup({Orig, New}, Token);
4071 if (AT)
4072 return QualType(AT, 0);
4073
4074 QualType Canonical = getCanonicalType(New);
4075
4076 AT = new (*this, alignof(AdjustedType))
4077 AdjustedType(Type::Adjusted, Orig, New, Canonical);
4078 Types.push_back(AT);
4079 AdjustedTypes.insert(AT, Token);
4080 return QualType(AT, 0);
4081}
4082
4084 llvm::FoldingSetInsertToken Token;
4085 AdjustedType *AT = AdjustedTypes.lookup({Orig, Decayed}, Token);
4086 if (AT)
4087 return QualType(AT, 0);
4088
4089 QualType Canonical = getCanonicalType(Decayed);
4090
4091 AT = new (*this, alignof(DecayedType)) DecayedType(Orig, Decayed, Canonical);
4092 Types.push_back(AT);
4093 AdjustedTypes.insert(AT, Token);
4094 return QualType(AT, 0);
4095}
4096
4098 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
4099
4100 QualType Decayed;
4101
4102 // C99 6.7.5.3p7:
4103 // A declaration of a parameter as "array of type" shall be
4104 // adjusted to "qualified pointer to type", where the type
4105 // qualifiers (if any) are those specified within the [ and ] of
4106 // the array type derivation.
4107 if (T->isArrayType())
4108 Decayed = getArrayDecayedType(T);
4109
4110 // C99 6.7.5.3p8:
4111 // A declaration of a parameter as "function returning type"
4112 // shall be adjusted to "pointer to function returning type", as
4113 // in 6.3.2.1.
4114 if (T->isFunctionType())
4115 Decayed = getPointerType(T);
4116
4117 return getDecayedType(T, Decayed);
4118}
4119
4121 if (Ty->isArrayParameterType())
4122 return Ty;
4123 assert(Ty->isConstantArrayType() && "Ty must be an array type.");
4124 QualType DTy = Ty.getDesugaredType(*this);
4125 const auto *ATy = cast<ConstantArrayType>(DTy);
4126 llvm::FoldingSetNodeID ID;
4127 ATy->Profile(ID, *this, ATy->getElementType(), ATy->getZExtSize(),
4128 ATy->getSizeExpr(), ATy->getSizeModifier(),
4129 ATy->getIndexTypeQualifiers().getAsOpaqueValue());
4130 llvm::FoldingSetInsertToken Token;
4131 ArrayParameterType *AT = ArrayParameterTypes.lookup(ID, Token);
4132 if (AT)
4133 return QualType(AT, 0);
4134
4135 QualType Canonical;
4136 if (!DTy.isCanonical()) {
4137 Canonical = getArrayParameterType(getCanonicalType(Ty));
4138
4139 // Get the new insert position for the node we care about.
4140 AT = ArrayParameterTypes.lookup(ID, Token);
4141 assert(!AT && "Shouldn't be in the map!");
4142 }
4143
4144 AT = new (*this, alignof(ArrayParameterType))
4145 ArrayParameterType(ATy, Canonical);
4146 Types.push_back(AT);
4147 ArrayParameterTypes.insert(AT, Token);
4148 return QualType(AT, 0);
4149}
4150
4151/// getBlockPointerType - Return the uniqued reference to the type for
4152/// a pointer to the specified block.
4154 assert(T->isFunctionType() && "block of function types only");
4155 // Unique pointers, to guarantee there is only one block of a particular
4156 // structure.
4157 llvm::FoldingSetInsertToken Token;
4158 if (BlockPointerType *PT = BlockPointerTypes.lookup(T, Token))
4159 return QualType(PT, 0);
4160
4161 // If the block pointee type isn't canonical, this won't be a canonical
4162 // type either so fill in the canonical type field.
4163 QualType Canonical;
4164 if (!T.isCanonical()) {
4166
4167 assert(!BlockPointerTypes.lookup(T, Token) && "Shouldn't be in the map!");
4168 }
4169 auto *New =
4170 new (*this, alignof(BlockPointerType)) BlockPointerType(T, Canonical);
4171 Types.push_back(New);
4172 BlockPointerTypes.insert(New, Token);
4173 return QualType(New, 0);
4174}
4175
4176/// getLValueReferenceType - Return the uniqued reference to the type for an
4177/// lvalue reference to the specified type.
4179ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
4180 assert((!T->isPlaceholderType() ||
4181 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
4182 "Unresolved placeholder type");
4183
4184 // Unique pointers, to guarantee there is only one pointer of a particular
4185 // structure.
4186 llvm::FoldingSetInsertToken Token;
4187 if (LValueReferenceType *RT =
4188 LValueReferenceTypes.lookup({T, SpelledAsLValue}, Token))
4189 return QualType(RT, 0);
4190
4191 const auto *InnerRef = T->getAs<ReferenceType>();
4192
4193 // If the referencee type isn't canonical, this won't be a canonical type
4194 // either, so fill in the canonical type field.
4195 QualType Canonical;
4196 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
4197 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
4198 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
4199
4200 assert(!LValueReferenceTypes.lookup({T, SpelledAsLValue}, Token) &&
4201 "Shouldn't be in the map!");
4202 }
4203
4204 auto *New = new (*this, alignof(LValueReferenceType))
4205 LValueReferenceType(T, Canonical, SpelledAsLValue);
4206 Types.push_back(New);
4207 LValueReferenceTypes.insert(New, Token);
4208
4209 return QualType(New, 0);
4210}
4211
4212/// getRValueReferenceType - Return the uniqued reference to the type for an
4213/// rvalue reference to the specified type.
4215 assert((!T->isPlaceholderType() ||
4216 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
4217 "Unresolved placeholder type");
4218
4219 // Unique pointers, to guarantee there is only one pointer of a particular
4220 // structure.
4221 llvm::FoldingSetInsertToken Token;
4222 if (RValueReferenceType *RT = RValueReferenceTypes.lookup({T, false}, Token))
4223 return QualType(RT, 0);
4224
4225 const auto *InnerRef = T->getAs<ReferenceType>();
4226
4227 // If the referencee type isn't canonical, this won't be a canonical type
4228 // either, so fill in the canonical type field.
4229 QualType Canonical;
4230 if (InnerRef || !T.isCanonical()) {
4231 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
4232 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
4233
4234 assert(!RValueReferenceTypes.lookup({T, false}, Token) &&
4235 "Shouldn't be in the map!");
4236 }
4237
4238 auto *New = new (*this, alignof(RValueReferenceType))
4239 RValueReferenceType(T, Canonical);
4240 Types.push_back(New);
4241 RValueReferenceTypes.insert(New, Token);
4242 return QualType(New, 0);
4243}
4244
4246 NestedNameSpecifier Qualifier,
4247 const CXXRecordDecl *Cls) const {
4248 if (!Qualifier) {
4249 assert(Cls && "At least one of Qualifier or Cls must be provided");
4250 Qualifier = NestedNameSpecifier(getCanonicalTagType(Cls).getTypePtr());
4251 } else if (!Cls) {
4252 Cls = Qualifier.getAsRecordDecl();
4253 }
4254 // Unique pointers, to guarantee there is only one pointer of a particular
4255 // structure.
4256 llvm::FoldingSetNodeID ID;
4257 MemberPointerType::Profile(ID, T, Qualifier, Cls);
4258
4259 llvm::FoldingSetInsertToken Token;
4260 if (MemberPointerType *PT = MemberPointerTypes.lookup(ID, Token))
4261 return QualType(PT, 0);
4262
4263 NestedNameSpecifier CanonicalQualifier = [&] {
4264 if (!Cls)
4265 return Qualifier.getCanonical();
4266 NestedNameSpecifier R(getCanonicalTagType(Cls).getTypePtr());
4267 assert(R.isCanonical());
4268 return R;
4269 }();
4270 // If the pointee or class type isn't canonical, this won't be a canonical
4271 // type either, so fill in the canonical type field.
4272 QualType Canonical;
4273 if (!T.isCanonical() || Qualifier != CanonicalQualifier) {
4274 Canonical =
4275 getMemberPointerType(getCanonicalType(T), CanonicalQualifier, Cls);
4276 assert(!cast<MemberPointerType>(Canonical)->isSugared());
4277 // Get the new insert position for the node we care about.
4278 [[maybe_unused]] MemberPointerType *NewIP =
4279 MemberPointerTypes.lookup(ID, Token);
4280 assert(!NewIP && "Shouldn't be in the map!");
4281 }
4282 auto *New = new (*this, alignof(MemberPointerType))
4283 MemberPointerType(T, Qualifier, Canonical);
4284 Types.push_back(New);
4285 MemberPointerTypes.insert(New, Token);
4286 return QualType(New, 0);
4287}
4288
4289/// getConstantArrayType - Return the unique reference to the type for an
4290/// array of the specified element type.
4292 const llvm::APInt &ArySizeIn,
4293 const Expr *SizeExpr,
4295 unsigned IndexTypeQuals) const {
4296 assert((EltTy->isDependentType() ||
4297 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
4298 "Constant array of VLAs is illegal!");
4299
4300 // We only need the size as part of the type if it's instantiation-dependent.
4301 if (SizeExpr && !SizeExpr->isInstantiationDependent())
4302 SizeExpr = nullptr;
4303
4304 // Convert the array size into a canonical width matching the pointer size for
4305 // the target.
4306 llvm::APInt ArySize(ArySizeIn);
4307 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
4308
4309 // The type stores only the CVR bits of the index qualifiers, so key on
4310 // those.
4311 IndexTypeQuals &= Qualifiers::CVRMask;
4312
4313 llvm::FoldingSetNodeID ID;
4314 ConstantArrayType::Profile(ID, *this, EltTy, ArySize.getZExtValue(), SizeExpr,
4315 ASM, IndexTypeQuals);
4316
4317 llvm::FoldingSetInsertToken Token;
4318 if (ConstantArrayType *ATP = ConstantArrayTypes.lookup(ID, Token))
4319 return QualType(ATP, 0);
4320
4321 // If the element type isn't canonical or has qualifiers, or the array bound
4322 // is instantiation-dependent, this won't be a canonical type either, so fill
4323 // in the canonical type field.
4324 QualType Canon;
4325 // FIXME: Check below should look for qualifiers behind sugar.
4326 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) {
4327 SplitQualType canonSplit = getCanonicalType(EltTy).split();
4328 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr,
4329 ASM, IndexTypeQuals);
4330 Canon = getQualifiedType(Canon, canonSplit.Quals);
4331
4332 // Get the new insert position for the node we care about.
4333 ConstantArrayType *NewIP = ConstantArrayTypes.lookup(ID, Token);
4334 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4335 }
4336
4337 auto *New = ConstantArrayType::Create(*this, EltTy, Canon, ArySize, SizeExpr,
4338 ASM, IndexTypeQuals);
4339 ConstantArrayTypes.insert(New, Token);
4340 Types.push_back(New);
4341 return QualType(New, 0);
4342}
4343
4344/// getVariableArrayDecayedType - Turns the given type, which may be
4345/// variably-modified, into the corresponding type with all the known
4346/// sizes replaced with [*].
4348 // Vastly most common case.
4349 if (!type->isVariablyModifiedType()) return type;
4350
4351 QualType result;
4352
4353 SplitQualType split = type.getSplitDesugaredType();
4354 const Type *ty = split.Ty;
4355 switch (ty->getTypeClass()) {
4356#define TYPE(Class, Base)
4357#define ABSTRACT_TYPE(Class, Base)
4358#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4359#include "clang/AST/TypeNodes.inc"
4360 llvm_unreachable("didn't desugar past all non-canonical types?");
4361
4362 // These types should never be variably-modified.
4363 case Type::Builtin:
4364 case Type::Complex:
4365 case Type::Vector:
4366 case Type::DependentVector:
4367 case Type::ExtVector:
4368 case Type::DependentSizedExtVector:
4369 case Type::ConstantMatrix:
4370 case Type::DependentSizedMatrix:
4371 case Type::DependentAddressSpace:
4372 case Type::ObjCObject:
4373 case Type::ObjCInterface:
4374 case Type::ObjCObjectPointer:
4375 case Type::Record:
4376 case Type::Enum:
4377 case Type::UnresolvedUsing:
4378 case Type::TypeOfExpr:
4379 case Type::TypeOf:
4380 case Type::Decltype:
4381 case Type::UnaryTransform:
4382 case Type::DependentName:
4383 case Type::InjectedClassName:
4384 case Type::TemplateSpecialization:
4385 case Type::TemplateTypeParm:
4386 case Type::SubstTemplateTypeParmPack:
4387 case Type::SubstBuiltinTemplatePack:
4388 case Type::Auto:
4389 case Type::DeducedTemplateSpecialization:
4390 case Type::PackExpansion:
4391 case Type::PackIndexing:
4392 case Type::BitInt:
4393 case Type::DependentBitInt:
4394 case Type::ArrayParameter:
4395 case Type::HLSLAttributedResource:
4396 case Type::HLSLInlineSpirv:
4397 case Type::OverflowBehavior:
4398 llvm_unreachable("type should never be variably-modified");
4399
4400 // These types can be variably-modified but should never need to
4401 // further decay.
4402 case Type::FunctionNoProto:
4403 case Type::FunctionProto:
4404 case Type::BlockPointer:
4405 case Type::MemberPointer:
4406 case Type::Pipe:
4407 return type;
4408
4409 // These types can be variably-modified. All these modifications
4410 // preserve structure except as noted by comments.
4411 // TODO: if we ever care about optimizing VLAs, there are no-op
4412 // optimizations available here.
4413 case Type::Pointer:
4416 break;
4417
4418 case Type::LValueReference: {
4419 const auto *lv = cast<LValueReferenceType>(ty);
4420 result = getLValueReferenceType(
4421 getVariableArrayDecayedType(lv->getPointeeType()),
4422 lv->isSpelledAsLValue());
4423 break;
4424 }
4425
4426 case Type::RValueReference: {
4427 const auto *lv = cast<RValueReferenceType>(ty);
4428 result = getRValueReferenceType(
4429 getVariableArrayDecayedType(lv->getPointeeType()));
4430 break;
4431 }
4432
4433 case Type::Atomic: {
4434 const auto *at = cast<AtomicType>(ty);
4435 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
4436 break;
4437 }
4438
4439 case Type::ConstantArray: {
4440 const auto *cat = cast<ConstantArrayType>(ty);
4441 result = getConstantArrayType(
4442 getVariableArrayDecayedType(cat->getElementType()),
4443 cat->getSize(),
4444 cat->getSizeExpr(),
4445 cat->getSizeModifier(),
4446 cat->getIndexTypeCVRQualifiers());
4447 break;
4448 }
4449
4450 case Type::DependentSizedArray: {
4451 const auto *dat = cast<DependentSizedArrayType>(ty);
4453 getVariableArrayDecayedType(dat->getElementType()), dat->getSizeExpr(),
4454 dat->getSizeModifier(), dat->getIndexTypeCVRQualifiers());
4455 break;
4456 }
4457
4458 // Turn incomplete types into [*] types.
4459 case Type::IncompleteArray: {
4460 const auto *iat = cast<IncompleteArrayType>(ty);
4461 result =
4463 /*size*/ nullptr, ArraySizeModifier::Normal,
4464 iat->getIndexTypeCVRQualifiers());
4465 break;
4466 }
4467
4468 // Turn VLA types into [*] types.
4469 case Type::VariableArray: {
4470 const auto *vat = cast<VariableArrayType>(ty);
4471 result =
4473 /*size*/ nullptr, ArraySizeModifier::Star,
4474 vat->getIndexTypeCVRQualifiers());
4475 break;
4476 }
4477 }
4478
4479 // Apply the top-level qualifiers from the original.
4480 return getQualifiedType(result, split.Quals);
4481}
4482
4483/// getVariableArrayType - Returns a non-unique reference to the type for a
4484/// variable array of the specified element type.
4487 unsigned IndexTypeQuals) const {
4488 // Since we don't unique expressions, it isn't possible to unique VLA's
4489 // that have an expression provided for their size.
4490 QualType Canon;
4491
4492 // Be sure to pull qualifiers off the element type.
4493 // FIXME: Check below should look for qualifiers behind sugar.
4494 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
4495 SplitQualType canonSplit = getCanonicalType(EltTy).split();
4496 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
4497 IndexTypeQuals);
4498 Canon = getQualifiedType(Canon, canonSplit.Quals);
4499 }
4500
4501 auto *New = new (*this, alignof(VariableArrayType))
4502 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals);
4503
4504 VariableArrayTypes.push_back(New);
4505 Types.push_back(New);
4506 return QualType(New, 0);
4507}
4508
4509/// getDependentSizedArrayType - Returns a non-unique reference to
4510/// the type for a dependently-sized array of the specified element
4511/// type.
4515 unsigned elementTypeQuals) const {
4516 assert((!numElements || numElements->isTypeDependent() ||
4517 numElements->isValueDependent()) &&
4518 "Size must be type- or value-dependent!");
4519
4520 SplitQualType canonElementType = getCanonicalType(elementType).split();
4521
4522 llvm::FoldingSetInsertToken Token;
4523 llvm::FoldingSetNodeID ID;
4525 ID, *this, numElements ? QualType(canonElementType.Ty, 0) : elementType,
4526 ASM, elementTypeQuals, numElements);
4527
4528 // Look for an existing type with these properties.
4529 DependentSizedArrayType *canonTy = DependentSizedArrayTypes.lookup(ID, Token);
4530
4531 // Dependently-sized array types that do not have a specified number
4532 // of elements will have their sizes deduced from a dependent
4533 // initializer.
4534 if (!numElements) {
4535 if (canonTy)
4536 return QualType(canonTy, 0);
4537
4538 auto *newType = new (*this, alignof(DependentSizedArrayType))
4539 DependentSizedArrayType(elementType, QualType(), numElements, ASM,
4540 elementTypeQuals);
4541 DependentSizedArrayTypes.insert(newType, Token);
4542 Types.push_back(newType);
4543 return QualType(newType, 0);
4544 }
4545
4546 // If we don't have one, build one.
4547 if (!canonTy) {
4548 canonTy = new (*this, alignof(DependentSizedArrayType))
4549 DependentSizedArrayType(QualType(canonElementType.Ty, 0), QualType(),
4550 numElements, ASM, elementTypeQuals);
4551 DependentSizedArrayTypes.insert(canonTy, Token);
4552 Types.push_back(canonTy);
4553 }
4554
4555 // Apply qualifiers from the element type to the array.
4556 QualType canon = getQualifiedType(QualType(canonTy,0),
4557 canonElementType.Quals);
4558
4559 // If we didn't need extra canonicalization for the element type or the size
4560 // expression, then just use that as our result.
4561 if (QualType(canonElementType.Ty, 0) == elementType &&
4562 canonTy->getSizeExpr() == numElements)
4563 return canon;
4564
4565 // Otherwise, we need to build a type which follows the spelling
4566 // of the element type.
4567 auto *sugaredType = new (*this, alignof(DependentSizedArrayType))
4568 DependentSizedArrayType(elementType, canon, numElements, ASM,
4569 elementTypeQuals);
4570 Types.push_back(sugaredType);
4571 return QualType(sugaredType, 0);
4572}
4573
4576 unsigned elementTypeQuals) const {
4577 llvm::FoldingSetNodeID ID;
4578 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
4579
4580 llvm::FoldingSetInsertToken Token;
4581 if (IncompleteArrayType *iat = IncompleteArrayTypes.lookup(ID, Token))
4582 return QualType(iat, 0);
4583
4584 // If the element type isn't canonical, this won't be a canonical type
4585 // either, so fill in the canonical type field. We also have to pull
4586 // qualifiers off the element type.
4587 QualType canon;
4588
4589 // FIXME: Check below should look for qualifiers behind sugar.
4590 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
4591 SplitQualType canonSplit = getCanonicalType(elementType).split();
4592 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
4593 ASM, elementTypeQuals);
4594 canon = getQualifiedType(canon, canonSplit.Quals);
4595
4596 // Get the new insert position for the node we care about.
4597 IncompleteArrayType *existing = IncompleteArrayTypes.lookup(ID, Token);
4598 assert(!existing && "Shouldn't be in the map!"); (void) existing;
4599 }
4600
4601 auto *newType = new (*this, alignof(IncompleteArrayType))
4602 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
4603
4604 IncompleteArrayTypes.insert(newType, Token);
4605 Types.push_back(newType);
4606 return QualType(newType, 0);
4607}
4608
4611#define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS) \
4612 {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount::getScalable(ELTS), \
4613 NUMVECTORS};
4614
4615#define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS) \
4616 {ELTTY, llvm::ElementCount::getScalable(ELTS), NUMVECTORS};
4617
4618 switch (Ty->getKind()) {
4619 default:
4620 llvm_unreachable("Unsupported builtin vector type");
4621
4622#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4623 ElBits, NF, IsSigned) \
4624 case BuiltinType::Id: \
4625 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4626 llvm::ElementCount::getScalable(NumEls), NF};
4627#define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4628 ElBits, NF) \
4629 case BuiltinType::Id: \
4630 return {ElBits == 16 ? HalfTy : (ElBits == 32 ? FloatTy : DoubleTy), \
4631 llvm::ElementCount::getScalable(NumEls), NF};
4632#define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4633 ElBits, NF) \
4634 case BuiltinType::Id: \
4635 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4636#define SVE_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4637 ElBits, NF) \
4638 case BuiltinType::Id: \
4639 return {MFloat8Ty, llvm::ElementCount::getScalable(NumEls), NF};
4640#define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4641 case BuiltinType::Id: \
4642 return {BoolTy, llvm::ElementCount::getScalable(NumEls), NF};
4643#include "clang/Basic/AArch64ACLETypes.def"
4644
4645#define RVV_VECTOR_TYPE_INT(Name, Id, SingletonId, NumEls, ElBits, NF, \
4646 IsSigned) \
4647 case BuiltinType::Id: \
4648 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4649 llvm::ElementCount::getScalable(NumEls), NF};
4650#define RVV_VECTOR_TYPE_FLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4651 case BuiltinType::Id: \
4652 return {ElBits == 16 ? Float16Ty : (ElBits == 32 ? FloatTy : DoubleTy), \
4653 llvm::ElementCount::getScalable(NumEls), NF};
4654#define RVV_VECTOR_TYPE_BFLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4655 case BuiltinType::Id: \
4656 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4657#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4658 case BuiltinType::Id: \
4659 return {BoolTy, llvm::ElementCount::getScalable(NumEls), 1};
4660#include "clang/Basic/RISCVVTypes.def"
4661 }
4662}
4663
4664/// getExternrefType - Return a WebAssembly externref type, which represents an
4665/// opaque reference to a host value.
4667 if (Target->getTriple().isWasm() && Target->hasFeature("reference-types")) {
4668#define WASM_REF_TYPE(Name, MangledName, Id, SingletonId, AS) \
4669 if (BuiltinType::Id == BuiltinType::WasmExternRef) \
4670 return SingletonId;
4671#include "clang/Basic/WebAssemblyReferenceTypes.def"
4672 }
4673 llvm_unreachable(
4674 "shouldn't try to generate type externref outside WebAssembly target");
4675}
4676
4677/// getScalableVectorType - Return the unique reference to a scalable vector
4678/// type of the specified element type and size. VectorType must be a built-in
4679/// type.
4681 unsigned NumFields) const {
4682 auto K = llvm::ScalableVecTyKey{EltTy, NumElts, NumFields};
4683 if (auto It = ScalableVecTyMap.find(K); It != ScalableVecTyMap.end())
4684 return It->second;
4685
4686 if (Target->hasAArch64ACLETypes()) {
4687 uint64_t EltTySize = getTypeSize(EltTy);
4688
4689#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4690 ElBits, NF, IsSigned) \
4691 if (EltTy->hasIntegerRepresentation() && !EltTy->isBooleanType() && \
4692 EltTy->hasSignedIntegerRepresentation() == IsSigned && \
4693 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4694 return ScalableVecTyMap[K] = SingletonId; \
4695 }
4696#define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4697 ElBits, NF) \
4698 if (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4699 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4700 return ScalableVecTyMap[K] = SingletonId; \
4701 }
4702#define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4703 ElBits, NF) \
4704 if (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4705 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4706 return ScalableVecTyMap[K] = SingletonId; \
4707 }
4708#define SVE_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4709 ElBits, NF) \
4710 if (EltTy->isMFloat8Type() && EltTySize == ElBits && \
4711 NumElts == (NumEls * NF) && NumFields == 1) { \
4712 return ScalableVecTyMap[K] = SingletonId; \
4713 }
4714#define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4715 if (EltTy->isBooleanType() && NumElts == (NumEls * NF) && NumFields == 1) \
4716 return ScalableVecTyMap[K] = SingletonId;
4717#include "clang/Basic/AArch64ACLETypes.def"
4718 } else if (Target->hasRISCVVTypes()) {
4719 uint64_t EltTySize = getTypeSize(EltTy);
4720#define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned, \
4721 IsFP, IsBF) \
4722 if (!EltTy->isBooleanType() && \
4723 ((EltTy->hasIntegerRepresentation() && \
4724 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \
4725 (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4726 IsFP && !IsBF) || \
4727 (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4728 IsBF && !IsFP)) && \
4729 EltTySize == ElBits && NumElts == NumEls && NumFields == NF) \
4730 return ScalableVecTyMap[K] = SingletonId;
4731#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4732 if (EltTy->isBooleanType() && NumElts == NumEls) \
4733 return ScalableVecTyMap[K] = SingletonId;
4734#include "clang/Basic/RISCVVTypes.def"
4735 }
4736 return QualType();
4737}
4738
4739/// getVectorType - Return the unique reference to a vector type of
4740/// the specified element type and size. VectorType must be a built-in type.
4742 VectorKind VecKind) const {
4743 assert(vecType->isBuiltinType() ||
4744 (vecType->isBitIntType() &&
4745 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4746 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits())));
4747
4748 // Check if we've already instantiated a vector of this type.
4749 llvm::FoldingSetNodeID ID;
4750 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
4751
4752 llvm::FoldingSetInsertToken Token;
4753 if (VectorType *VTP = VectorTypes.lookup(ID, Token))
4754 return QualType(VTP, 0);
4755
4756 // If the element type isn't canonical, this won't be a canonical type either,
4757 // so fill in the canonical type field.
4758 QualType Canonical;
4759 if (!vecType.isCanonical()) {
4760 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
4761
4762 // Get the new insert position for the node we care about.
4763 VectorType *NewIP = VectorTypes.lookup(ID, Token);
4764 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4765 }
4766 auto *New = new (*this, alignof(VectorType))
4767 VectorType(vecType, NumElts, Canonical, VecKind);
4768 VectorTypes.insert(New, Token);
4769 Types.push_back(New);
4770 return QualType(New, 0);
4771}
4772
4774 SourceLocation AttrLoc,
4775 VectorKind VecKind) const {
4776 llvm::FoldingSetNodeID ID;
4777 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
4778 VecKind);
4779 llvm::FoldingSetInsertToken Token;
4780 DependentVectorType *Canon = DependentVectorTypes.lookup(ID, Token);
4782
4783 if (Canon) {
4784 New = new (*this, alignof(DependentVectorType)) DependentVectorType(
4785 VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
4786 } else {
4787 QualType CanonVecTy = getCanonicalType(VecType);
4788 if (CanonVecTy == VecType) {
4789 New = new (*this, alignof(DependentVectorType))
4790 DependentVectorType(VecType, QualType(), SizeExpr, AttrLoc, VecKind);
4791
4792 DependentVectorType *CanonCheck = DependentVectorTypes.lookup(ID, Token);
4793 assert(!CanonCheck &&
4794 "Dependent-sized vector_size canonical type broken");
4795 (void)CanonCheck;
4796 DependentVectorTypes.insert(New, Token);
4797 } else {
4798 QualType CanonTy = getDependentVectorType(CanonVecTy, SizeExpr,
4799 SourceLocation(), VecKind);
4800 New = new (*this, alignof(DependentVectorType))
4801 DependentVectorType(VecType, CanonTy, SizeExpr, AttrLoc, VecKind);
4802 }
4803 }
4804
4805 Types.push_back(New);
4806 return QualType(New, 0);
4807}
4808
4809/// getExtVectorType - Return the unique reference to an extended vector type of
4810/// the specified element type and size. VectorType must be a built-in type.
4812 unsigned NumElts) const {
4813 assert(vecType->isBuiltinType() || vecType->isDependentType() ||
4814 (vecType->isBitIntType() &&
4815 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4816 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits())));
4817
4818 // Check if we've already instantiated a vector of this type.
4819 llvm::FoldingSetNodeID ID;
4820 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
4822 llvm::FoldingSetInsertToken Token;
4823 if (VectorType *VTP = VectorTypes.lookup(ID, Token))
4824 return QualType(VTP, 0);
4825
4826 // If the element type isn't canonical, this won't be a canonical type either,
4827 // so fill in the canonical type field.
4828 QualType Canonical;
4829 if (!vecType.isCanonical()) {
4830 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
4831
4832 // Get the new insert position for the node we care about.
4833 VectorType *NewIP = VectorTypes.lookup(ID, Token);
4834 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4835 }
4836 auto *New = new (*this, alignof(ExtVectorType))
4837 ExtVectorType(vecType, NumElts, Canonical);
4838 VectorTypes.insert(New, Token);
4839 Types.push_back(New);
4840 return QualType(New, 0);
4841}
4842
4845 Expr *SizeExpr,
4846 SourceLocation AttrLoc) const {
4847 llvm::FoldingSetNodeID ID;
4849 SizeExpr);
4850
4851 llvm::FoldingSetInsertToken Token;
4853 DependentSizedExtVectorTypes.lookup(ID, Token);
4855 if (Canon) {
4856 // We already have a canonical version of this array type; use it as
4857 // the canonical type for a newly-built type.
4858 New = new (*this, alignof(DependentSizedExtVectorType))
4859 DependentSizedExtVectorType(vecType, QualType(Canon, 0), SizeExpr,
4860 AttrLoc);
4861 } else {
4862 QualType CanonVecTy = getCanonicalType(vecType);
4863 if (CanonVecTy == vecType) {
4864 New = new (*this, alignof(DependentSizedExtVectorType))
4865 DependentSizedExtVectorType(vecType, QualType(), SizeExpr, AttrLoc);
4866
4867 DependentSizedExtVectorType *CanonCheck =
4868 DependentSizedExtVectorTypes.lookup(ID, Token);
4869 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
4870 (void)CanonCheck;
4871 DependentSizedExtVectorTypes.insert(New, Token);
4872 } else {
4873 QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
4874 SourceLocation());
4875 New = new (*this, alignof(DependentSizedExtVectorType))
4876 DependentSizedExtVectorType(vecType, CanonExtTy, SizeExpr, AttrLoc);
4877 }
4878 }
4879
4880 Types.push_back(New);
4881 return QualType(New, 0);
4882}
4883
4885 QualType ElementTy, unsigned NumRows, unsigned NumColumns,
4886 std::optional<MatrixType::LayoutKind> Layout) const {
4887 llvm::FoldingSetNodeID ID;
4888 ConstantMatrixType::Profile(ID, ElementTy, NumRows, NumColumns, Layout,
4889 Type::ConstantMatrix);
4890
4891 assert(MatrixType::isValidElementType(ElementTy, getLangOpts()) &&
4892 "need a valid element type");
4893 assert(NumRows > 0 && NumRows <= LangOpts.MaxMatrixDimension &&
4894 NumColumns > 0 && NumColumns <= LangOpts.MaxMatrixDimension &&
4895 "need valid matrix dimensions");
4896 llvm::FoldingSetInsertToken Token;
4897 if (ConstantMatrixType *MTP = MatrixTypes.lookup(ID, Token))
4898 return QualType(MTP, 0);
4899
4900 QualType Canonical;
4901 if (Layout || !ElementTy.isCanonical()) {
4902 Canonical = getConstantMatrixType(getCanonicalType(ElementTy), NumRows,
4903 NumColumns, std::nullopt);
4904
4905 ConstantMatrixType *NewIP = MatrixTypes.lookup(ID, Token);
4906 assert(!NewIP && "Matrix type shouldn't already exist in the map");
4907 (void)NewIP;
4908 }
4909
4910 auto *New = new (*this, alignof(ConstantMatrixType))
4911 ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical, Layout);
4912 MatrixTypes.insert(New, Token);
4913 Types.push_back(New);
4914 return QualType(New, 0);
4915}
4916
4918 Expr *RowExpr,
4919 Expr *ColumnExpr,
4920 SourceLocation AttrLoc) const {
4921 QualType CanonElementTy = getCanonicalType(ElementTy);
4922 llvm::FoldingSetNodeID ID;
4923 DependentSizedMatrixType::Profile(ID, *this, CanonElementTy, RowExpr,
4924 ColumnExpr);
4925
4926 llvm::FoldingSetInsertToken Token;
4927 DependentSizedMatrixType *Canon = DependentSizedMatrixTypes.lookup(ID, Token);
4928
4929 if (!Canon) {
4930 Canon = new (*this, alignof(DependentSizedMatrixType))
4931 DependentSizedMatrixType(CanonElementTy, QualType(), RowExpr,
4932 ColumnExpr, AttrLoc);
4933#ifndef NDEBUG
4934 DependentSizedMatrixType *CanonCheck =
4935 DependentSizedMatrixTypes.lookup(ID, Token);
4936 assert(!CanonCheck && "Dependent-sized matrix canonical type broken");
4937#endif
4938 DependentSizedMatrixTypes.insert(Canon, Token);
4939 Types.push_back(Canon);
4940 }
4941
4942 // Already have a canonical version of the matrix type
4943 //
4944 // If it exactly matches the requested type, use it directly.
4945 if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr &&
4946 Canon->getRowExpr() == ColumnExpr)
4947 return QualType(Canon, 0);
4948
4949 // Use Canon as the canonical type for newly-built type.
4951 DependentSizedMatrixType(ElementTy, QualType(Canon, 0), RowExpr,
4952 ColumnExpr, AttrLoc);
4953 Types.push_back(New);
4954 return QualType(New, 0);
4955}
4956
4959 MatrixType::LayoutKind Layout) const {
4960 Qualifiers Quals = T.getQualifiers();
4961 const Type *Ty = T->getUnqualifiedDesugaredType();
4962
4963 if (const auto *MT = dyn_cast<ConstantMatrixType>(Ty))
4964 return getQualifiedType(getConstantMatrixType(MT->getElementType(),
4965 MT->getNumRows(),
4966 MT->getNumColumns(), Layout),
4967 Quals);
4968
4969 const auto *CAT = dyn_cast<ConstantArrayType>(Ty);
4970 if (!CAT)
4971 return T;
4972
4974 getMatrixTypeWithLayout(CAT->getElementType(), Layout), CAT->getSize(),
4975 CAT->getSizeExpr(), CAT->getSizeModifier(),
4976 CAT->getIndexTypeCVRQualifiers());
4977 if (isa<ArrayParameterType>(CAT))
4979
4980 return getQualifiedType(Result, Quals);
4981}
4982
4984 Expr *AddrSpaceExpr,
4985 SourceLocation AttrLoc) const {
4986 assert(AddrSpaceExpr->isInstantiationDependent());
4987
4988 QualType canonPointeeType = getCanonicalType(PointeeType);
4989
4990 llvm::FoldingSetInsertToken Token;
4991 llvm::FoldingSetNodeID ID;
4992 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
4993 AddrSpaceExpr);
4994
4995 DependentAddressSpaceType *canonTy =
4996 DependentAddressSpaceTypes.lookup(ID, Token);
4997
4998 if (!canonTy) {
4999 canonTy = new (*this, alignof(DependentAddressSpaceType))
5000 DependentAddressSpaceType(canonPointeeType, QualType(), AddrSpaceExpr,
5001 AttrLoc);
5002 DependentAddressSpaceTypes.insert(canonTy, Token);
5003 Types.push_back(canonTy);
5004 }
5005
5006 if (canonPointeeType == PointeeType &&
5007 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
5008 return QualType(canonTy, 0);
5009
5010 auto *sugaredType = new (*this, alignof(DependentAddressSpaceType))
5011 DependentAddressSpaceType(PointeeType, QualType(canonTy, 0),
5012 AddrSpaceExpr, AttrLoc);
5013 Types.push_back(sugaredType);
5014 return QualType(sugaredType, 0);
5015}
5016
5017/// Determine whether \p T is canonical as the result type of a function.
5019 return T.isCanonical() &&
5020 (T.getObjCLifetime() == Qualifiers::OCL_None ||
5021 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
5022}
5023
5024/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
5025QualType
5027 const FunctionType::ExtInfo &Info) const {
5028 // FIXME: This assertion cannot be enabled (yet) because the ObjC rewriter
5029 // functionality creates a function without a prototype regardless of
5030 // language mode (so it makes them even in C++). Once the rewriter has been
5031 // fixed, this assertion can be enabled again.
5032 //assert(!LangOpts.requiresStrictPrototypes() &&
5033 // "strict prototypes are disabled");
5034
5035 // Unique functions, to guarantee there is only one function of a particular
5036 // structure.
5037 llvm::FoldingSetNodeID ID;
5038 FunctionNoProtoType::Profile(ID, ResultTy, Info);
5039
5040 llvm::FoldingSetInsertToken Token;
5041 if (FunctionNoProtoType *FT = FunctionNoProtoTypes.lookup(ID, Token))
5042 return QualType(FT, 0);
5043
5044 QualType Canonical;
5045 if (!isCanonicalResultType(ResultTy)) {
5046 Canonical =
5048
5049 // Get the new insert position for the node we care about.
5050 FunctionNoProtoType *NewIP = FunctionNoProtoTypes.lookup(ID, Token);
5051 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
5052 }
5053
5054 auto *New = new (*this, alignof(FunctionNoProtoType))
5055 FunctionNoProtoType(ResultTy, Canonical, Info);
5056 Types.push_back(New);
5057 FunctionNoProtoTypes.insert(New, Token);
5058 return QualType(New, 0);
5059}
5060
5063 CanQualType CanResultType = getCanonicalType(ResultType);
5064
5065 // Canonical result types do not have ARC lifetime qualifiers.
5066 if (CanResultType.getQualifiers().hasObjCLifetime()) {
5067 Qualifiers Qs = CanResultType.getQualifiers();
5068 Qs.removeObjCLifetime();
5070 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
5071 }
5072
5073 return CanResultType;
5074}
5075
5077 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
5078 if (ESI.Type == EST_None)
5079 return true;
5080 if (!NoexceptInType)
5081 return false;
5082
5083 // C++17 onwards: exception specification is part of the type, as a simple
5084 // boolean "can this function type throw".
5085 if (ESI.Type == EST_BasicNoexcept)
5086 return true;
5087
5088 // A noexcept(expr) specification is (possibly) canonical if expr is
5089 // value-dependent.
5090 if (ESI.Type == EST_DependentNoexcept)
5091 return true;
5092
5093 // A dynamic exception specification is canonical if it only contains pack
5094 // expansions (so we can't tell whether it's non-throwing) and all its
5095 // contained types are canonical.
5096 if (ESI.Type == EST_Dynamic) {
5097 bool AnyPackExpansions = false;
5098 for (QualType ET : ESI.Exceptions) {
5099 if (!ET.isCanonical())
5100 return false;
5101 if (ET->getAs<PackExpansionType>())
5102 AnyPackExpansions = true;
5103 }
5104 return AnyPackExpansions;
5105 }
5106
5107 return false;
5108}
5109
5110QualType ASTContext::getFunctionTypeInternal(
5111 QualType ResultTy, ArrayRef<QualType> ArgArray,
5112 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
5113 size_t NumArgs = ArgArray.size();
5114
5115 // Unique functions, to guarantee there is only one function of a particular
5116 // structure.
5117 llvm::FoldingSetNodeID ID;
5118 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
5119 *this);
5120
5121 QualType Canonical;
5122 bool Unique = false;
5123
5124 llvm::FoldingSetInsertToken Token;
5125 if (FunctionProtoType *FPT = FunctionProtoTypes.lookup(ID, Token)) {
5126 QualType Existing = QualType(FPT, 0);
5127
5128 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
5129 // it so long as our exception specification doesn't contain a dependent
5130 // noexcept expression, or we're just looking for a canonical type.
5131 // Otherwise, we're going to need to create a type
5132 // sugar node to hold the concrete expression.
5133 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
5134 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
5135 return Existing;
5136
5137 // We need a new type sugar node for this one, to hold the new noexcept
5138 // expression. We do no canonicalization here, but that's OK since we don't
5139 // expect to see the same noexcept expression much more than once.
5140 Canonical = getCanonicalType(Existing);
5141 Unique = true;
5142 }
5143
5144 bool NoexceptInType = getLangOpts().CPlusPlus17;
5145 bool IsCanonicalExceptionSpec =
5147
5148 // Determine whether the type being created is already canonical or not.
5149 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
5150 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
5151 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
5152 if (!ArgArray[i].isCanonicalAsParam())
5153 isCanonical = false;
5154
5155 if (OnlyWantCanonical)
5156 assert(isCanonical &&
5157 "given non-canonical parameters constructing canonical type");
5158
5159 // If this type isn't canonical, get the canonical version of it if we don't
5160 // already have it. The exception spec is only partially part of the
5161 // canonical type, and only in C++17 onwards.
5162 if (!isCanonical && Canonical.isNull()) {
5163 SmallVector<QualType, 16> CanonicalArgs;
5164 CanonicalArgs.reserve(NumArgs);
5165 for (unsigned i = 0; i != NumArgs; ++i)
5166 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
5167
5168 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
5169 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
5170 CanonicalEPI.HasTrailingReturn = false;
5171
5172 if (IsCanonicalExceptionSpec) {
5173 // Exception spec is already OK.
5174 } else if (NoexceptInType) {
5175 switch (EPI.ExceptionSpec.Type) {
5177 // We don't know yet. It shouldn't matter what we pick here; no-one
5178 // should ever look at this.
5179 [[fallthrough]];
5180 case EST_None: case EST_MSAny: case EST_NoexceptFalse:
5181 CanonicalEPI.ExceptionSpec.Type = EST_None;
5182 break;
5183
5184 // A dynamic exception specification is almost always "not noexcept",
5185 // with the exception that a pack expansion might expand to no types.
5186 case EST_Dynamic: {
5187 bool AnyPacks = false;
5188 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
5189 if (ET->getAs<PackExpansionType>())
5190 AnyPacks = true;
5191 ExceptionTypeStorage.push_back(getCanonicalType(ET));
5192 }
5193 if (!AnyPacks)
5194 CanonicalEPI.ExceptionSpec.Type = EST_None;
5195 else {
5196 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
5197 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
5198 }
5199 break;
5200 }
5201
5202 case EST_DynamicNone:
5203 case EST_BasicNoexcept:
5204 case EST_NoexceptTrue:
5205 case EST_NoThrow:
5206 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
5207 break;
5208
5210 llvm_unreachable("dependent noexcept is already canonical");
5211 }
5212 } else {
5213 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
5214 }
5215
5216 // Adjust the canonical function result type.
5217 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
5218 Canonical =
5219 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
5220
5221 // Get the new insert position for the node we care about.
5222 FunctionProtoType *NewIP = FunctionProtoTypes.lookup(ID, Token);
5223 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
5224 }
5225
5226 // Compute the needed size to hold this FunctionProtoType and the
5227 // various trailing objects.
5228 auto ESH = FunctionProtoType::getExceptionSpecSize(
5229 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
5230 size_t Size = FunctionProtoType::totalSizeToAlloc<
5231 QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields,
5232 FunctionType::FunctionTypeExtraAttributeInfo,
5233 FunctionType::FunctionTypeArmAttributes, FunctionType::ExceptionType,
5234 Expr *, FunctionDecl *, FunctionProtoType::ExtParameterInfo, Qualifiers,
5235 FunctionEffect, EffectConditionExpr>(
5238 EPI.requiresFunctionProtoTypeArmAttributes(), ESH.NumExceptionType,
5239 ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
5240 EPI.ExtParameterInfos ? NumArgs : 0,
5242 EPI.FunctionEffects.conditions().size());
5243
5244 auto *FTP = (FunctionProtoType *)Allocate(Size, alignof(FunctionProtoType));
5245 FunctionProtoType::ExtProtoInfo newEPI = EPI;
5246 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
5247 Types.push_back(FTP);
5248 if (!Unique)
5249 FunctionProtoTypes.insert(FTP, Token);
5250 if (!EPI.FunctionEffects.empty())
5251 AnyFunctionEffects = true;
5252 return QualType(FTP, 0);
5253}
5254
5255QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
5256 llvm::FoldingSetInsertToken Token;
5257 if (PipeType *PT = PipeTypes.lookup({T, ReadOnly}, Token))
5258 return QualType(PT, 0);
5259
5260 // If the pipe element type isn't canonical, this won't be a canonical type
5261 // either, so fill in the canonical type field.
5262 QualType Canonical;
5263 if (!T.isCanonical()) {
5264 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
5265
5266 assert(!PipeTypes.lookup({T, ReadOnly}, Token) &&
5267 "Shouldn't be in the map!");
5268 }
5269 auto *New = new (*this, alignof(PipeType)) PipeType(T, Canonical, ReadOnly);
5270 Types.push_back(New);
5271 PipeTypes.insert(New, Token);
5272 return QualType(New, 0);
5273}
5274
5276 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
5277 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
5278 : Ty;
5279}
5280
5282 return getPipeType(T, true);
5283}
5284
5286 return getPipeType(T, false);
5287}
5288
5289QualType ASTContext::getBitIntType(bool IsUnsigned, unsigned NumBits) const {
5290 auto Key = std::make_pair(unsigned(IsUnsigned), NumBits);
5291
5292 llvm::FoldingSetInsertToken Token;
5293 if (BitIntType *EIT = BitIntTypes.lookup(Key, Token))
5294 return QualType(EIT, 0);
5295
5296 auto *New = new (*this, alignof(BitIntType)) BitIntType(IsUnsigned, NumBits);
5297 BitIntTypes.insert(New, Token);
5298 Types.push_back(New);
5299 return QualType(New, 0);
5300}
5301
5303 Expr *NumBitsExpr) const {
5304 assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent");
5305 llvm::FoldingSetNodeID ID;
5306 DependentBitIntType::Profile(ID, *this, IsUnsigned, NumBitsExpr);
5307
5308 llvm::FoldingSetInsertToken Token;
5309 if (DependentBitIntType *Existing = DependentBitIntTypes.lookup(ID, Token))
5310 return QualType(Existing, 0);
5311
5312 auto *New = new (*this, alignof(DependentBitIntType))
5313 DependentBitIntType(IsUnsigned, NumBitsExpr);
5314 DependentBitIntTypes.insert(New, Token);
5315
5316 Types.push_back(New);
5317 return QualType(New, 0);
5318}
5319
5322 using Kind = PredefinedSugarType::Kind;
5323
5324 if (auto *Target = PredefinedSugarTypes[llvm::to_underlying(KD)];
5325 Target != nullptr)
5326 return QualType(Target, 0);
5327
5328 auto getCanonicalType = [](const ASTContext &Ctx, Kind KDI) -> QualType {
5329 switch (KDI) {
5330 // size_t (C99TC3 6.5.3.4), signed size_t (C++23 5.13.2) and
5331 // ptrdiff_t (C99TC3 6.5.6) Although these types are not built-in, they
5332 // are part of the core language and are widely used. Using
5333 // PredefinedSugarType makes these types as named sugar types rather than
5334 // standard integer types, enabling better hints and diagnostics.
5335 case Kind::SizeT:
5336 return Ctx.getFromTargetType(Ctx.Target->getSizeType());
5337 case Kind::SignedSizeT:
5338 return Ctx.getFromTargetType(Ctx.Target->getSignedSizeType());
5339 case Kind::PtrdiffT:
5340 return Ctx.getFromTargetType(Ctx.Target->getPtrDiffType(LangAS::Default));
5341 }
5342 llvm_unreachable("unexpected kind");
5343 };
5344 auto *New = new (*this, alignof(PredefinedSugarType))
5345 PredefinedSugarType(KD, &Idents.get(PredefinedSugarType::getName(KD)),
5346 getCanonicalType(*this, static_cast<Kind>(KD)));
5347 Types.push_back(New);
5348 PredefinedSugarTypes[llvm::to_underlying(KD)] = New;
5349 return QualType(New, 0);
5350}
5351
5353 NestedNameSpecifier Qualifier,
5354 const TypeDecl *Decl) const {
5355 if (auto *Tag = dyn_cast<TagDecl>(Decl))
5356 return getTagType(Keyword, Qualifier, Tag,
5357 /*OwnsTag=*/false);
5358 if (auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
5359 return getTypedefType(Keyword, Qualifier, Typedef);
5360 if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(Decl))
5361 return getUnresolvedUsingType(Keyword, Qualifier, UD);
5362
5364 assert(!Qualifier);
5365 return QualType(Decl->TypeForDecl, 0);
5366}
5367
5369 if (auto *Tag = dyn_cast<TagDecl>(TD))
5370 return getCanonicalTagType(Tag);
5371 if (auto *TN = dyn_cast<TypedefNameDecl>(TD))
5372 return getCanonicalType(TN->getUnderlyingType());
5373 if (const auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(TD))
5375 assert(TD->TypeForDecl);
5376 return TD->TypeForDecl->getCanonicalTypeUnqualified();
5377}
5378
5380 if (const auto *TD = dyn_cast<TagDecl>(Decl))
5381 return getCanonicalTagType(TD);
5382 if (const auto *TD = dyn_cast<TypedefNameDecl>(Decl);
5383 isa_and_nonnull<TypedefDecl, TypeAliasDecl>(TD))
5385 /*Qualifier=*/std::nullopt, TD);
5386 if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl))
5387 return getCanonicalUnresolvedUsingType(Using);
5388
5389 assert(Decl->TypeForDecl);
5390 return QualType(Decl->TypeForDecl, 0);
5391}
5392
5393/// getTypedefType - Return the unique reference to the type for the
5394/// specified typedef name decl.
5397 NestedNameSpecifier Qualifier,
5398 const TypedefNameDecl *Decl, QualType UnderlyingType,
5399 std::optional<bool> TypeMatchesDeclOrNone) const {
5400 if (!TypeMatchesDeclOrNone) {
5401 QualType DeclUnderlyingType = Decl->getUnderlyingType();
5402 assert(!DeclUnderlyingType.isNull());
5403 if (UnderlyingType.isNull())
5404 UnderlyingType = DeclUnderlyingType;
5405 else
5406 assert(hasSameType(UnderlyingType, DeclUnderlyingType));
5407 TypeMatchesDeclOrNone = UnderlyingType == DeclUnderlyingType;
5408 } else {
5409 // FIXME: This is a workaround for a serialization cycle: assume the decl
5410 // underlying type is not available; don't touch it.
5411 assert(!UnderlyingType.isNull());
5412 }
5413
5414 if (Keyword == ElaboratedTypeKeyword::None && !Qualifier &&
5415 *TypeMatchesDeclOrNone) {
5416 if (Decl->TypeForDecl)
5417 return QualType(Decl->TypeForDecl, 0);
5418
5419 auto *NewType = new (*this, alignof(TypedefType))
5420 TypedefType(Type::Typedef, Keyword, Qualifier, Decl, UnderlyingType,
5421 !*TypeMatchesDeclOrNone);
5422
5423 Types.push_back(NewType);
5424 Decl->TypeForDecl = NewType;
5425 return QualType(NewType, 0);
5426 }
5427
5428 llvm::FoldingSetNodeID ID;
5429 TypedefType::Profile(ID, Keyword, Qualifier, Decl,
5430 *TypeMatchesDeclOrNone ? QualType() : UnderlyingType);
5431
5432 llvm::FoldingSetInsertToken Token;
5433 if (FoldingSetPlaceholder<TypedefType> *Placeholder =
5434 TypedefTypes.lookup(ID, Token))
5435 return QualType(Placeholder->getType(), 0);
5436
5437 void *Mem =
5438 Allocate(TypedefType::totalSizeToAlloc<FoldingSetPlaceholder<TypedefType>,
5440 1, !!Qualifier, !*TypeMatchesDeclOrNone),
5441 alignof(TypedefType));
5442 auto *NewType =
5443 new (Mem) TypedefType(Type::Typedef, Keyword, Qualifier, Decl,
5444 UnderlyingType, !*TypeMatchesDeclOrNone);
5445 auto *Placeholder = new (NewType->getFoldingSetPlaceholder())
5447 TypedefTypes.insert(Placeholder, Token);
5448 Types.push_back(NewType);
5449 return QualType(NewType, 0);
5450}
5451
5453 NestedNameSpecifier Qualifier,
5454 const UsingShadowDecl *D,
5455 QualType UnderlyingType) const {
5456 // FIXME: This is expensive to compute every time!
5457 if (UnderlyingType.isNull()) {
5458 const auto *UD = cast<UsingDecl>(D->getIntroducer());
5459 UnderlyingType =
5462 UD->getQualifier(), cast<TypeDecl>(D->getTargetDecl()));
5463 }
5464
5465 llvm::FoldingSetNodeID ID;
5466 UsingType::Profile(ID, Keyword, Qualifier, D, UnderlyingType);
5467
5468 llvm::FoldingSetInsertToken Token;
5469 if (const UsingType *T = UsingTypes.lookup(ID, Token))
5470 return QualType(T, 0);
5471
5472 assert(!UnderlyingType.hasLocalQualifiers());
5473
5474 assert(
5476 UnderlyingType));
5477
5478 void *Mem =
5479 Allocate(UsingType::totalSizeToAlloc<NestedNameSpecifier>(!!Qualifier),
5480 alignof(UsingType));
5481 UsingType *T = new (Mem) UsingType(Keyword, Qualifier, D, UnderlyingType);
5482 Types.push_back(T);
5483 UsingTypes.insert(T, Token);
5484 return QualType(T, 0);
5485}
5486
5487TagType *ASTContext::getTagTypeInternal(ElaboratedTypeKeyword Keyword,
5488 NestedNameSpecifier Qualifier,
5489 const TagDecl *TD, bool OwnsTag,
5490 bool IsInjected,
5491 const Type *CanonicalType,
5492 bool WithFoldingSetNode) const {
5493 auto [TC, Size] = [&] {
5494 switch (TD->getDeclKind()) {
5495 case Decl::Enum:
5496 static_assert(alignof(EnumType) == alignof(TagType));
5497 return std::make_tuple(Type::Enum, sizeof(EnumType));
5498 case Decl::ClassTemplatePartialSpecialization:
5499 case Decl::ClassTemplateSpecialization:
5500 case Decl::CXXRecord:
5501 static_assert(alignof(RecordType) == alignof(TagType));
5502 static_assert(alignof(InjectedClassNameType) == alignof(TagType));
5503 if (cast<CXXRecordDecl>(TD)->hasInjectedClassType())
5504 return std::make_tuple(Type::InjectedClassName,
5505 sizeof(InjectedClassNameType));
5506 [[fallthrough]];
5507 case Decl::Record:
5508 return std::make_tuple(Type::Record, sizeof(RecordType));
5509 default:
5510 llvm_unreachable("unexpected decl kind");
5511 }
5512 }();
5513
5514 if (Qualifier) {
5515 static_assert(alignof(NestedNameSpecifier) <= alignof(TagType));
5516 Size = llvm::alignTo(Size, alignof(NestedNameSpecifier)) +
5517 sizeof(NestedNameSpecifier);
5518 }
5519 void *Mem;
5520 if (WithFoldingSetNode) {
5521 // FIXME: It would be more profitable to tail allocate the folding set node
5522 // from the type, instead of the other way around, due to the greater
5523 // alignment requirements of the type. But this makes it harder to deal with
5524 // the different type node sizes. This would require either uniquing from
5525 // different folding sets, or having the folding setaccept a
5526 // contextual parameter which is not fixed at construction.
5527 Mem = Allocate(
5528 sizeof(TagTypeFoldingSetPlaceholder) +
5529 TagTypeFoldingSetPlaceholder::getOffset() + Size,
5530 std::max(alignof(TagTypeFoldingSetPlaceholder), alignof(TagType)));
5531 auto *T = new (Mem) TagTypeFoldingSetPlaceholder();
5532 Mem = T->getTagType();
5533 } else {
5534 Mem = Allocate(Size, alignof(TagType));
5535 }
5536
5537 auto *T = [&, TC = TC]() -> TagType * {
5538 switch (TC) {
5539 case Type::Enum: {
5540 assert(isa<EnumDecl>(TD));
5541 auto *T = new (Mem) EnumType(TC, Keyword, Qualifier, TD, OwnsTag,
5542 IsInjected, CanonicalType);
5543 assert(reinterpret_cast<void *>(T) ==
5544 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5545 "TagType must be the first base of EnumType");
5546 return T;
5547 }
5548 case Type::Record: {
5549 assert(isa<RecordDecl>(TD));
5550 auto *T = new (Mem) RecordType(TC, Keyword, Qualifier, TD, OwnsTag,
5551 IsInjected, CanonicalType);
5552 assert(reinterpret_cast<void *>(T) ==
5553 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5554 "TagType must be the first base of RecordType");
5555 return T;
5556 }
5557 case Type::InjectedClassName: {
5558 auto *T = new (Mem) InjectedClassNameType(Keyword, Qualifier, TD,
5559 IsInjected, CanonicalType);
5560 assert(reinterpret_cast<void *>(T) ==
5561 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5562 "TagType must be the first base of InjectedClassNameType");
5563 return T;
5564 }
5565 default:
5566 llvm_unreachable("unexpected type class");
5567 }
5568 }();
5569 assert(T->getKeyword() == Keyword);
5570 assert(T->getQualifier() == Qualifier);
5571 assert(T->getDecl() == TD);
5572 assert(T->isInjected() == IsInjected);
5573 assert(T->isTagOwned() == OwnsTag);
5574 assert((T->isCanonicalUnqualified()
5575 ? QualType()
5576 : T->getCanonicalTypeInternal()) == QualType(CanonicalType, 0));
5577 Types.push_back(T);
5578 return T;
5579}
5580
5581static const TagDecl *getNonInjectedClassName(const TagDecl *TD) {
5582 if (const auto *RD = dyn_cast<CXXRecordDecl>(TD);
5583 RD && RD->isInjectedClassName())
5584 return cast<TagDecl>(RD->getDeclContext());
5585 return TD;
5586}
5587
5590 if (TD->TypeForDecl)
5591 return TD->TypeForDecl->getCanonicalTypeUnqualified();
5592
5593 const Type *CanonicalType = getTagTypeInternal(
5595 /*Qualifier=*/std::nullopt, TD,
5596 /*OwnsTag=*/false, /*IsInjected=*/false, /*CanonicalType=*/nullptr,
5597 /*WithFoldingSetNode=*/false);
5598 TD->TypeForDecl = CanonicalType;
5599 return CanQualType::CreateUnsafe(QualType(CanonicalType, 0));
5600}
5601
5603 NestedNameSpecifier Qualifier,
5604 const TagDecl *TD, bool OwnsTag) const {
5605
5606 const TagDecl *NonInjectedTD = ::getNonInjectedClassName(TD);
5607 bool IsInjected = TD != NonInjectedTD;
5608
5609 ElaboratedTypeKeyword PreferredKeyword =
5612 NonInjectedTD->getTagKind());
5613
5614 if (Keyword == PreferredKeyword && !Qualifier && !OwnsTag) {
5615 if (const Type *T = TD->TypeForDecl; T && !T->isCanonicalUnqualified())
5616 return QualType(T, 0);
5617
5618 const Type *CanonicalType = getCanonicalTagType(NonInjectedTD).getTypePtr();
5619 const Type *T =
5620 getTagTypeInternal(Keyword,
5621 /*Qualifier=*/std::nullopt, NonInjectedTD,
5622 /*OwnsTag=*/false, IsInjected, CanonicalType,
5623 /*WithFoldingSetNode=*/false);
5624 TD->TypeForDecl = T;
5625 return QualType(T, 0);
5626 }
5627
5628 llvm::FoldingSetNodeID ID;
5629 TagTypeFoldingSetPlaceholder::Profile(ID, Keyword, Qualifier, NonInjectedTD,
5630 OwnsTag, IsInjected);
5631
5632 llvm::FoldingSetInsertToken Token;
5633 if (TagTypeFoldingSetPlaceholder *T = TagTypes.lookup(ID, Token))
5634 return QualType(T->getTagType(), 0);
5635
5636 const Type *CanonicalType = getCanonicalTagType(NonInjectedTD).getTypePtr();
5637 TagType *T =
5638 getTagTypeInternal(Keyword, Qualifier, NonInjectedTD, OwnsTag, IsInjected,
5639 CanonicalType, /*WithFoldingSetNode=*/true);
5640 TagTypes.insert(TagTypeFoldingSetPlaceholder::fromTagType(T), Token);
5641 return QualType(T, 0);
5642}
5643
5644bool ASTContext::computeBestEnumTypes(bool IsPacked, unsigned NumNegativeBits,
5645 unsigned NumPositiveBits,
5646 QualType &BestType,
5647 QualType &BestPromotionType) {
5648 unsigned IntWidth = Target->getIntWidth();
5649 unsigned CharWidth = Target->getCharWidth();
5650 unsigned ShortWidth = Target->getShortWidth();
5651 bool EnumTooLarge = false;
5652 unsigned BestWidth;
5653 if (NumNegativeBits) {
5654 // If there is a negative value, figure out the smallest integer type (of
5655 // int/long/longlong) that fits.
5656 // If it's packed, check also if it fits a char or a short.
5657 if (IsPacked && NumNegativeBits <= CharWidth &&
5658 NumPositiveBits < CharWidth) {
5659 BestType = SignedCharTy;
5660 BestWidth = CharWidth;
5661 } else if (IsPacked && NumNegativeBits <= ShortWidth &&
5662 NumPositiveBits < ShortWidth) {
5663 BestType = ShortTy;
5664 BestWidth = ShortWidth;
5665 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
5666 BestType = IntTy;
5667 BestWidth = IntWidth;
5668 } else {
5669 BestWidth = Target->getLongWidth();
5670
5671 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
5672 BestType = LongTy;
5673 } else {
5674 BestWidth = Target->getLongLongWidth();
5675
5676 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
5677 EnumTooLarge = true;
5678 BestType = LongLongTy;
5679 }
5680 }
5681 BestPromotionType = (BestWidth <= IntWidth ? IntTy : BestType);
5682 } else {
5683 // If there is no negative value, figure out the smallest type that fits
5684 // all of the enumerator values.
5685 // If it's packed, check also if it fits a char or a short.
5686 if (IsPacked && NumPositiveBits <= CharWidth) {
5687 BestType = UnsignedCharTy;
5688 BestPromotionType = IntTy;
5689 BestWidth = CharWidth;
5690 } else if (IsPacked && NumPositiveBits <= ShortWidth) {
5691 BestType = UnsignedShortTy;
5692 BestPromotionType = IntTy;
5693 BestWidth = ShortWidth;
5694 } else if (NumPositiveBits <= IntWidth) {
5695 BestType = UnsignedIntTy;
5696 BestWidth = IntWidth;
5697 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5699 : IntTy;
5700 } else if (NumPositiveBits <= (BestWidth = Target->getLongWidth())) {
5701 BestType = UnsignedLongTy;
5702 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5704 : LongTy;
5705 } else {
5706 BestWidth = Target->getLongLongWidth();
5707 if (NumPositiveBits > BestWidth) {
5708 // This can happen with bit-precise integer types, but those are not
5709 // allowed as the type for an enumerator per C23 6.7.2.2p4 and p12.
5710 // FIXME: GCC uses __int128_t and __uint128_t for cases that fit within
5711 // a 128-bit integer, we should consider doing the same.
5712 EnumTooLarge = true;
5713 }
5714 BestType = UnsignedLongLongTy;
5715 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5717 : LongLongTy;
5718 }
5719 }
5720 return EnumTooLarge;
5721}
5722
5724 assert((T->isIntegralType(*this) || T->isEnumeralType()) &&
5725 "Integral type required!");
5726 unsigned BitWidth = getIntWidth(T);
5727
5728 if (Value.isUnsigned() || Value.isNonNegative()) {
5729 if (T->isSignedIntegerOrEnumerationType())
5730 --BitWidth;
5731 return Value.getActiveBits() <= BitWidth;
5732 }
5733 return Value.getSignificantBits() <= BitWidth;
5734}
5735
5736UnresolvedUsingType *ASTContext::getUnresolvedUsingTypeInternal(
5738 const UnresolvedUsingTypenameDecl *D, llvm::FoldingSetInsertToken Token,
5739 const Type *CanonicalType) const {
5740 void *Mem = Allocate(
5741 UnresolvedUsingType::totalSizeToAlloc<
5743 !!Token, !!Qualifier),
5744 alignof(UnresolvedUsingType));
5745 auto *T = new (Mem) UnresolvedUsingType(Keyword, Qualifier, D, CanonicalType);
5746 if (Token) {
5747 auto *Placeholder = new (T->getFoldingSetPlaceholder())
5749 UnresolvedUsingTypes.insert(Placeholder, Token);
5750 }
5751 Types.push_back(T);
5752 return T;
5753}
5754
5756 const UnresolvedUsingTypenameDecl *D) const {
5757 D = D->getCanonicalDecl();
5758 if (D->TypeForDecl)
5759 return D->TypeForDecl->getCanonicalTypeUnqualified();
5760
5761 const Type *CanonicalType =
5762 getUnresolvedUsingTypeInternal(ElaboratedTypeKeyword::None,
5763 /*Qualifier=*/std::nullopt, D,
5764 /*Token=*/{}, /*CanonicalType=*/nullptr);
5765 D->TypeForDecl = CanonicalType;
5766 return CanQualType::CreateUnsafe(QualType(CanonicalType, 0));
5767}
5768
5771 NestedNameSpecifier Qualifier,
5772 const UnresolvedUsingTypenameDecl *D) const {
5773 if (Keyword == ElaboratedTypeKeyword::None && !Qualifier) {
5774 if (const Type *T = D->TypeForDecl; T && !T->isCanonicalUnqualified())
5775 return QualType(T, 0);
5776
5777 const Type *CanonicalType = getCanonicalUnresolvedUsingType(D).getTypePtr();
5778 const Type *T =
5779 getUnresolvedUsingTypeInternal(ElaboratedTypeKeyword::None,
5780 /*Qualifier=*/std::nullopt, D,
5781 /*Token=*/{}, CanonicalType);
5782 D->TypeForDecl = T;
5783 return QualType(T, 0);
5784 }
5785
5786 llvm::FoldingSetNodeID ID;
5787 UnresolvedUsingType::Profile(ID, Keyword, Qualifier, D);
5788
5789 llvm::FoldingSetInsertToken Token;
5791 UnresolvedUsingTypes.lookup(ID, Token))
5792 return QualType(Placeholder->getType(), 0);
5793 assert(Token);
5794
5795 const Type *CanonicalType = getCanonicalUnresolvedUsingType(D).getTypePtr();
5796 const Type *T = getUnresolvedUsingTypeInternal(Keyword, Qualifier, D, Token,
5797 CanonicalType);
5798 return QualType(T, 0);
5799}
5800
5802 QualType modifiedType,
5803 QualType equivalentType,
5804 const Attr *attr) const {
5805 llvm::FoldingSetNodeID id;
5806 AttributedType::Profile(id, *this, attrKind, modifiedType, equivalentType,
5807 attr);
5808
5809 llvm::FoldingSetInsertToken Token;
5810 AttributedType *type = AttributedTypes.lookup(id, Token);
5811 if (type) return QualType(type, 0);
5812
5813 assert(!attr || attr->getKind() == attrKind);
5814
5815 QualType canon = getCanonicalType(equivalentType);
5816 type = new (*this, alignof(AttributedType))
5817 AttributedType(canon, attrKind, attr, modifiedType, equivalentType);
5818
5819 Types.push_back(type);
5820 AttributedTypes.insert(type, Token);
5821
5822 return QualType(type, 0);
5823}
5824
5826 QualType equivalentType) const {
5827 return getAttributedType(attr->getKind(), modifiedType, equivalentType, attr);
5828}
5829
5831 QualType modifiedType,
5832 QualType equivalentType) const {
5833 switch (nullability) {
5835 return getAttributedType(attr::TypeNonNull, modifiedType, equivalentType);
5836
5838 return getAttributedType(attr::TypeNullable, modifiedType, equivalentType);
5839
5841 return getAttributedType(attr::TypeNullableResult, modifiedType,
5842 equivalentType);
5843
5845 return getAttributedType(attr::TypeNullUnspecified, modifiedType,
5846 equivalentType);
5847 }
5848
5849 llvm_unreachable("Unknown nullability kind");
5850}
5851
5852QualType ASTContext::getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
5853 QualType Wrapped) const {
5854 llvm::FoldingSetNodeID ID;
5855 BTFTagAttributedType::Profile(ID, Wrapped, BTFAttr);
5856
5857 llvm::FoldingSetInsertToken Token;
5858 BTFTagAttributedType *Ty = BTFTagAttributedTypes.lookup(ID, Token);
5859 if (Ty)
5860 return QualType(Ty, 0);
5861
5862 QualType Canon = getCanonicalType(Wrapped);
5863 Ty = new (*this, alignof(BTFTagAttributedType))
5864 BTFTagAttributedType(Canon, Wrapped, BTFAttr);
5865
5866 Types.push_back(Ty);
5867 BTFTagAttributedTypes.insert(Ty, Token);
5868
5869 return QualType(Ty, 0);
5870}
5871
5873 QualType Underlying) const {
5874 const IdentifierInfo *II = Attr->getBehaviorKind();
5875 StringRef IdentName = II->getName();
5876 OverflowBehaviorType::OverflowBehaviorKind Kind;
5877 if (IdentName == "wrap") {
5878 Kind = OverflowBehaviorType::OverflowBehaviorKind::Wrap;
5879 } else if (IdentName == "trap") {
5880 Kind = OverflowBehaviorType::OverflowBehaviorKind::Trap;
5881 } else {
5882 return Underlying;
5883 }
5884
5885 return getOverflowBehaviorType(Kind, Underlying);
5886}
5887
5889 OverflowBehaviorType::OverflowBehaviorKind Kind,
5890 QualType Underlying) const {
5891 assert(!Underlying->isOverflowBehaviorType() &&
5892 "Cannot have underlying types that are themselves OBTs");
5893
5894 llvm::FoldingSetInsertToken Token;
5895 if (OverflowBehaviorType *OBT =
5896 OverflowBehaviorTypes.lookup({Underlying, Kind}, Token)) {
5897 return QualType(OBT, 0);
5898 }
5899
5900 QualType Canonical;
5901 if (!Underlying.isCanonical() || Underlying.hasLocalQualifiers()) {
5902 SplitQualType canonSplit = getCanonicalType(Underlying).split();
5903 Canonical = getOverflowBehaviorType(Kind, QualType(canonSplit.Ty, 0));
5904 Canonical = getQualifiedType(Canonical, canonSplit.Quals);
5905 assert(!OverflowBehaviorTypes.lookup({Underlying, Kind}, Token) &&
5906 "Shouldn't be in the map");
5907 }
5908
5909 OverflowBehaviorType *Ty = new (*this, alignof(OverflowBehaviorType))
5910 OverflowBehaviorType(*this, Canonical, Underlying, Kind);
5911
5912 Types.push_back(Ty);
5913 OverflowBehaviorTypes.insert(Ty, Token);
5914 return QualType(Ty, 0);
5915}
5916
5918 QualType Wrapped, QualType Contained,
5919 const HLSLAttributedResourceType::Attributes &Attrs) {
5920
5921 llvm::FoldingSetNodeID ID;
5922 HLSLAttributedResourceType::Profile(ID, *this, Wrapped, Contained, Attrs);
5923
5924 llvm::FoldingSetInsertToken Token;
5925 HLSLAttributedResourceType *Ty =
5926 HLSLAttributedResourceTypes.lookup(ID, Token);
5927 if (Ty)
5928 return QualType(Ty, 0);
5929
5930 Ty = new (*this, alignof(HLSLAttributedResourceType))
5931 HLSLAttributedResourceType(Wrapped, Contained, Attrs);
5932
5933 Types.push_back(Ty);
5934 HLSLAttributedResourceTypes.insert(Ty, Token);
5935
5936 return QualType(Ty, 0);
5937}
5938
5939QualType ASTContext::getHLSLInlineSpirvType(uint32_t Opcode, uint32_t Size,
5940 uint32_t Alignment,
5941 ArrayRef<SpirvOperand> Operands) {
5942 llvm::FoldingSetNodeID ID;
5943 HLSLInlineSpirvType::Profile(ID, Opcode, Size, Alignment, Operands);
5944
5945 llvm::FoldingSetInsertToken Token;
5946 HLSLInlineSpirvType *Ty = HLSLInlineSpirvTypes.lookup(ID, Token);
5947 if (Ty)
5948 return QualType(Ty, 0);
5949
5950 void *Mem = Allocate(
5951 HLSLInlineSpirvType::totalSizeToAlloc<SpirvOperand>(Operands.size()),
5952 alignof(HLSLInlineSpirvType));
5953
5954 Ty = new (Mem) HLSLInlineSpirvType(Opcode, Size, Alignment, Operands);
5955
5956 Types.push_back(Ty);
5957 HLSLInlineSpirvTypes.insert(Ty, Token);
5958
5959 return QualType(Ty, 0);
5960}
5961
5962/// Retrieve a substitution-result type.
5964 Decl *AssociatedDecl,
5965 unsigned Index,
5967 bool Final) const {
5968 auto Key =
5969 std::make_tuple(Replacement, AssociatedDecl, Index,
5970 PackIndex.toInternalRepresentation(), unsigned(Final));
5971 llvm::FoldingSetInsertToken Token;
5972 SubstTemplateTypeParmType *SubstParm =
5973 SubstTemplateTypeParmTypes.lookup(Key, Token);
5974
5975 if (!SubstParm) {
5976 void *Mem = Allocate(SubstTemplateTypeParmType::totalSizeToAlloc<QualType>(
5977 !Replacement.isCanonical()),
5978 alignof(SubstTemplateTypeParmType));
5979 SubstParm = new (Mem) SubstTemplateTypeParmType(Replacement, AssociatedDecl,
5980 Index, PackIndex, Final);
5981 Types.push_back(SubstParm);
5982 SubstTemplateTypeParmTypes.insert(SubstParm, Token);
5983 }
5984
5985 return QualType(SubstParm, 0);
5986}
5987
5990 unsigned Index, bool Final,
5991 const TemplateArgument &ArgPack) {
5992#ifndef NDEBUG
5993 for (const auto &P : ArgPack.pack_elements())
5994 assert(P.getKind() == TemplateArgument::Type && "Pack contains a non-type");
5995#endif
5996
5997 llvm::FoldingSetNodeID ID;
5998 SubstTemplateTypeParmPackType::Profile(ID, AssociatedDecl, Index, Final,
5999 ArgPack);
6000 llvm::FoldingSetInsertToken Token;
6001 if (SubstTemplateTypeParmPackType *SubstParm =
6002 SubstTemplateTypeParmPackTypes.lookup(ID, Token))
6003 return QualType(SubstParm, 0);
6004
6005 QualType Canon;
6006 {
6007 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(ArgPack);
6008 if (!AssociatedDecl->isCanonicalDecl() ||
6009 !CanonArgPack.structurallyEquals(ArgPack)) {
6011 AssociatedDecl->getCanonicalDecl(), Index, Final, CanonArgPack);
6012 [[maybe_unused]] const auto *Nothing =
6013 SubstTemplateTypeParmPackTypes.lookup(ID, Token);
6014 assert(!Nothing);
6015 }
6016 }
6017
6018 auto *SubstParm = new (*this, alignof(SubstTemplateTypeParmPackType))
6019 SubstTemplateTypeParmPackType(Canon, AssociatedDecl, Index, Final,
6020 ArgPack);
6021 Types.push_back(SubstParm);
6022 SubstTemplateTypeParmPackTypes.insert(SubstParm, Token);
6023 return QualType(SubstParm, 0);
6024}
6025
6028 assert(llvm::all_of(ArgPack.pack_elements(),
6029 [](const auto &P) {
6030 return P.getKind() == TemplateArgument::Type;
6031 }) &&
6032 "Pack contains a non-type");
6033
6034 llvm::FoldingSetNodeID ID;
6035 SubstBuiltinTemplatePackType::Profile(ID, ArgPack);
6036
6037 llvm::FoldingSetInsertToken Token;
6038 if (auto *T = SubstBuiltinTemplatePackTypes.lookup(ID, Token))
6039 return QualType(T, 0);
6040
6041 QualType Canon;
6042 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(ArgPack);
6043 if (!CanonArgPack.structurallyEquals(ArgPack)) {
6044 Canon = getSubstBuiltinTemplatePack(CanonArgPack);
6045 // Refresh Token, in case the recursive call above caused rehashing,
6046 // which would invalidate the bucket pointer.
6047 [[maybe_unused]] const auto *Nothing =
6048 SubstBuiltinTemplatePackTypes.lookup(ID, Token);
6049 assert(!Nothing);
6050 }
6051
6052 auto *PackType = new (*this, alignof(SubstBuiltinTemplatePackType))
6053 SubstBuiltinTemplatePackType(Canon, ArgPack);
6054 Types.push_back(PackType);
6055 SubstBuiltinTemplatePackTypes.insert(PackType, Token);
6056 return QualType(PackType, 0);
6057}
6058
6059/// Retrieve the template type parameter type for a template
6060/// parameter or parameter pack with the given depth, index, and (optionally)
6061/// name.
6063ASTContext::getTemplateTypeParmType(int Depth, int Index, bool ParameterPack,
6064 TemplateTypeParmDecl *TTPDecl) const {
6065 assert(Depth >= 0 && "Depth must be non-negative");
6066 assert(Index >= 0 && "Index must be non-negative");
6067
6068 auto Key = std::make_tuple(unsigned(Depth), unsigned(Index),
6069 unsigned(ParameterPack), TTPDecl);
6070 llvm::FoldingSetInsertToken Token;
6071 TemplateTypeParmType *TypeParm = TemplateTypeParmTypes.lookup(Key, Token);
6072
6073 if (TypeParm)
6074 return QualType(TypeParm, 0);
6075
6076 if (TTPDecl) {
6077 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
6078 TypeParm = new (*this, alignof(TemplateTypeParmType))
6079 TemplateTypeParmType(Depth, Index, ParameterPack, TTPDecl, Canon);
6080 } else
6081 TypeParm = new (*this, alignof(TemplateTypeParmType)) TemplateTypeParmType(
6082 Depth, Index, ParameterPack, /*TTPDecl=*/nullptr, /*Canon=*/QualType());
6083
6084 Types.push_back(TypeParm);
6085 TemplateTypeParmTypes.insert(TypeParm, Token);
6086
6087 return QualType(TypeParm, 0);
6088}
6089
6092 switch (Keyword) {
6093 // These are just themselves.
6099 return Keyword;
6100
6101 // These are equivalent.
6104
6105 // These are functionally equivalent, so relying on their equivalence is
6106 // IFNDR. By making them equivalent, we disallow overloading, which at least
6107 // can produce a diagnostic.
6110 }
6111 llvm_unreachable("unexpected keyword kind");
6112}
6113
6115 ElaboratedTypeKeyword Keyword, SourceLocation ElaboratedKeywordLoc,
6116 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKeywordLoc,
6117 TemplateName Name, SourceLocation NameLoc,
6118 const TemplateArgumentListInfo &SpecifiedArgs,
6119 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6121 Keyword, Name, SpecifiedArgs.arguments(), CanonicalArgs, Underlying);
6122
6125 ElaboratedKeywordLoc, QualifierLoc, TemplateKeywordLoc, NameLoc,
6126 SpecifiedArgs);
6127 return TSI;
6128}
6129
6132 ArrayRef<TemplateArgumentLoc> SpecifiedArgs,
6133 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6134 SmallVector<TemplateArgument, 4> SpecifiedArgVec;
6135 SpecifiedArgVec.reserve(SpecifiedArgs.size());
6136 for (const TemplateArgumentLoc &Arg : SpecifiedArgs)
6137 SpecifiedArgVec.push_back(Arg.getArgument());
6138
6139 return getTemplateSpecializationType(Keyword, Template, SpecifiedArgVec,
6140 CanonicalArgs, Underlying);
6141}
6142
6143[[maybe_unused]] static bool
6145 for (const TemplateArgument &Arg : Args)
6146 if (Arg.isPackExpansion())
6147 return true;
6148 return false;
6149}
6150
6153 ArrayRef<TemplateArgument> Args) const {
6154 assert(Template ==
6155 getCanonicalTemplateName(Template, /*IgnoreDeduced=*/true));
6157 Template.getAsDependentTemplateName()));
6158#ifndef NDEBUG
6159 for (const auto &Arg : Args)
6160 assert(Arg.structurallyEquals(getCanonicalTemplateArgument(Arg)));
6161#endif
6162
6163 llvm::FoldingSetNodeID ID;
6164 TemplateSpecializationType::Profile(ID, Keyword, Template, Args, QualType(),
6165 *this);
6166 llvm::FoldingSetInsertToken Token;
6167 if (auto *T = TemplateSpecializationTypes.lookup(ID, Token))
6168 return QualType(T, 0);
6169
6170 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
6171 sizeof(TemplateArgument) * Args.size(),
6172 alignof(TemplateSpecializationType));
6173 auto *Spec =
6174 new (Mem) TemplateSpecializationType(Keyword, Template,
6175 /*IsAlias=*/false, Args, QualType());
6176 assert(Spec->isDependentType() &&
6177 "canonical template specialization must be dependent");
6178 Types.push_back(Spec);
6179 TemplateSpecializationTypes.insert(Spec, Token);
6180 return QualType(Spec, 0);
6181}
6182
6185 ArrayRef<TemplateArgument> SpecifiedArgs,
6186 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6187 const auto *TD = Template.getAsTemplateDecl(/*IgnoreDeduced=*/true);
6188 bool IsTypeAlias = TD && TD->isTypeAlias();
6189 if (Underlying.isNull()) {
6190 TemplateName CanonTemplate =
6191 getCanonicalTemplateName(Template, /*IgnoreDeduced=*/true);
6192 ElaboratedTypeKeyword CanonKeyword =
6193 CanonTemplate.getAsDependentTemplateName()
6196 bool NonCanonical = Template != CanonTemplate || Keyword != CanonKeyword;
6198 if (CanonicalArgs.empty()) {
6199 CanonArgsVec = SmallVector<TemplateArgument, 4>(SpecifiedArgs);
6200 NonCanonical |= canonicalizeTemplateArguments(CanonArgsVec);
6201 CanonicalArgs = CanonArgsVec;
6202 } else {
6203 NonCanonical |= !llvm::equal(
6204 SpecifiedArgs, CanonicalArgs,
6205 [](const TemplateArgument &A, const TemplateArgument &B) {
6206 return A.structurallyEquals(B);
6207 });
6208 }
6209
6210 // We can get here with an alias template when the specialization
6211 // contains a pack expansion that does not match up with a parameter
6212 // pack, or a builtin template which cannot be resolved due to dependency.
6213 assert((!isa_and_nonnull<TypeAliasTemplateDecl>(TD) ||
6214 hasAnyPackExpansions(CanonicalArgs)) &&
6215 "Caller must compute aliased type");
6216 IsTypeAlias = false;
6217
6219 CanonKeyword, CanonTemplate, CanonicalArgs);
6220 if (!NonCanonical)
6221 return Underlying;
6222 }
6223 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
6224 sizeof(TemplateArgument) * SpecifiedArgs.size() +
6225 (IsTypeAlias ? sizeof(QualType) : 0),
6226 alignof(TemplateSpecializationType));
6227 auto *Spec = new (Mem) TemplateSpecializationType(
6228 Keyword, Template, IsTypeAlias, SpecifiedArgs, Underlying);
6229 Types.push_back(Spec);
6230 return QualType(Spec, 0);
6231}
6232
6235 llvm::FoldingSetInsertToken Token;
6236 ParenType *T = ParenTypes.lookup(InnerType, Token);
6237 if (T)
6238 return QualType(T, 0);
6239
6240 QualType Canon = InnerType;
6241 if (!Canon.isCanonical()) {
6242 Canon = getCanonicalType(InnerType);
6243 assert(!ParenTypes.lookup(InnerType, Token) &&
6244 "Paren canonical type broken");
6245 }
6246
6247 T = new (*this, alignof(ParenType)) ParenType(InnerType, Canon);
6248 Types.push_back(T);
6249 ParenTypes.insert(T, Token);
6250 return QualType(T, 0);
6251}
6252
6255 const IdentifierInfo *MacroII) const {
6256 QualType Canon = UnderlyingTy;
6257 if (!Canon.isCanonical())
6258 Canon = getCanonicalType(UnderlyingTy);
6259
6260 auto *newType = new (*this, alignof(MacroQualifiedType))
6261 MacroQualifiedType(UnderlyingTy, Canon, MacroII);
6262 Types.push_back(newType);
6263 return QualType(newType, 0);
6264}
6265
6268 const IdentifierInfo *Name) const {
6269 llvm::FoldingSetNodeID ID;
6270 DependentNameType::Profile(ID, Keyword, NNS, Name);
6271
6272 llvm::FoldingSetInsertToken Token;
6273 if (DependentNameType *T = DependentNameTypes.lookup(ID, Token))
6274 return QualType(T, 0);
6275
6276 ElaboratedTypeKeyword CanonKeyword =
6278 NestedNameSpecifier CanonNNS = NNS.getCanonical();
6279
6280 QualType Canon;
6281 if (CanonKeyword != Keyword || CanonNNS != NNS) {
6282 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
6283 [[maybe_unused]] DependentNameType *T =
6284 DependentNameTypes.lookup(ID, Token);
6285 assert(!T && "broken canonicalization");
6286 assert(Canon.isCanonical());
6287 }
6288
6289 DependentNameType *T = new (*this, alignof(DependentNameType))
6290 DependentNameType(Keyword, NNS, Name, Canon);
6291 Types.push_back(T);
6292 DependentNameTypes.insert(T, Token);
6293 return QualType(T, 0);
6294}
6295
6297 TemplateArgument Arg;
6298 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
6300 if (TTP->isParameterPack())
6301 ArgType = getPackExpansionType(ArgType, std::nullopt);
6302
6304 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
6305 QualType T =
6306 NTTP->getType().getNonPackExpansionType().getNonLValueExprType(*this);
6307 // For class NTTPs, ensure we include the 'const' so the type matches that
6308 // of a real template argument.
6309 // FIXME: It would be more faithful to model this as something like an
6310 // lvalue-to-rvalue conversion applied to a const-qualified lvalue.
6312 if (T->isRecordType()) {
6313 // C++ [temp.param]p8: An id-expression naming a non-type
6314 // template-parameter of class type T denotes a static storage duration
6315 // object of type const T.
6316 T.addConst();
6317 VK = VK_LValue;
6318 } else {
6319 VK = Expr::getValueKindForType(NTTP->getType());
6320 }
6321 Expr *E = new (*this)
6322 DeclRefExpr(*this, NTTP, /*RefersToEnclosingVariableOrCapture=*/false,
6323 T, VK, NTTP->getLocation());
6324
6325 if (NTTP->isParameterPack())
6326 E = new (*this) PackExpansionExpr(E, NTTP->getLocation(), std::nullopt);
6327 Arg = TemplateArgument(E, /*IsCanonical=*/false);
6328 } else {
6329 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
6331 /*Qualifier=*/std::nullopt, /*TemplateKeyword=*/false,
6332 TemplateName(TTP));
6333 if (TTP->isParameterPack())
6334 Arg = TemplateArgument(Name, /*NumExpansions=*/std::nullopt);
6335 else
6336 Arg = TemplateArgument(Name);
6337 }
6338
6339 if (Param->isTemplateParameterPack())
6340 Arg =
6341 TemplateArgument::CreatePackCopy(const_cast<ASTContext &>(*this), Arg);
6342
6343 return Arg;
6344}
6345
6347 UnsignedOrNone NumExpansions,
6348 bool ExpectPackInType) const {
6349 assert((!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) &&
6350 "Pack expansions must expand one or more parameter packs");
6351
6352 auto Key = std::make_pair(Pattern, NumExpansions.toInternalRepresentation());
6353
6354 llvm::FoldingSetInsertToken Token;
6355 PackExpansionType *T = PackExpansionTypes.lookup(Key, Token);
6356 if (T)
6357 return QualType(T, 0);
6358
6359 QualType Canon;
6360 if (!Pattern.isCanonical()) {
6361 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions,
6362 /*ExpectPackInType=*/false);
6363
6364 // Find the insert position again, in case we inserted an element into
6365 // PackExpansionTypes and invalidated our insert position.
6366 PackExpansionTypes.lookup(Key, Token);
6367 }
6368
6369 T = new (*this, alignof(PackExpansionType))
6370 PackExpansionType(Pattern, Canon, NumExpansions);
6371 Types.push_back(T);
6372 PackExpansionTypes.insert(T, Token);
6373 return QualType(T, 0);
6374}
6375
6376/// CmpProtocolNames - Comparison predicate for sorting protocols
6377/// alphabetically.
6378static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
6379 ObjCProtocolDecl *const *RHS) {
6380 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
6381}
6382
6384 if (Protocols.empty()) return true;
6385
6386 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
6387 return false;
6388
6389 for (unsigned i = 1; i != Protocols.size(); ++i)
6390 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
6391 Protocols[i]->getCanonicalDecl() != Protocols[i])
6392 return false;
6393 return true;
6394}
6395
6396static void
6398 // Sort protocols, keyed by name.
6399 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
6400
6401 // Canonicalize.
6402 for (ObjCProtocolDecl *&P : Protocols)
6403 P = P->getCanonicalDecl();
6404
6405 // Remove duplicates.
6406 auto ProtocolsEnd = llvm::unique(Protocols);
6407 Protocols.erase(ProtocolsEnd, Protocols.end());
6408}
6409
6411 ObjCProtocolDecl * const *Protocols,
6412 unsigned NumProtocols) const {
6413 return getObjCObjectType(BaseType, {}, ArrayRef(Protocols, NumProtocols),
6414 /*isKindOf=*/false);
6415}
6416
6418 QualType baseType,
6419 ArrayRef<QualType> typeArgs,
6421 bool isKindOf) const {
6422 // If the base type is an interface and there aren't any protocols or
6423 // type arguments to add, then the interface type will do just fine.
6424 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
6425 isa<ObjCInterfaceType>(baseType))
6426 return baseType;
6427
6428 // Look in the folding set for an existing type.
6429 llvm::FoldingSetNodeID ID;
6430 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
6431 llvm::FoldingSetInsertToken Token;
6432 if (ObjCObjectType *QT = ObjCObjectTypes.lookup(ID, Token))
6433 return QualType(QT, 0);
6434
6435 // Determine the type arguments to be used for canonicalization,
6436 // which may be explicitly specified here or written on the base
6437 // type.
6438 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
6439 if (effectiveTypeArgs.empty()) {
6440 if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
6441 effectiveTypeArgs = baseObject->getTypeArgs();
6442 }
6443
6444 // Build the canonical type, which has the canonical base type and a
6445 // sorted-and-uniqued list of protocols and the type arguments
6446 // canonicalized.
6447 QualType canonical;
6448 bool typeArgsAreCanonical = llvm::all_of(
6449 effectiveTypeArgs, [&](QualType type) { return type.isCanonical(); });
6450 bool protocolsSorted = areSortedAndUniqued(protocols);
6451 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
6452 // Determine the canonical type arguments.
6453 ArrayRef<QualType> canonTypeArgs;
6454 SmallVector<QualType, 4> canonTypeArgsVec;
6455 if (!typeArgsAreCanonical) {
6456 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
6457 for (auto typeArg : effectiveTypeArgs)
6458 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
6459 canonTypeArgs = canonTypeArgsVec;
6460 } else {
6461 canonTypeArgs = effectiveTypeArgs;
6462 }
6463
6464 ArrayRef<ObjCProtocolDecl *> canonProtocols;
6465 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
6466 if (!protocolsSorted) {
6467 canonProtocolsVec.append(protocols.begin(), protocols.end());
6468 SortAndUniqueProtocols(canonProtocolsVec);
6469 canonProtocols = canonProtocolsVec;
6470 } else {
6471 canonProtocols = protocols;
6472 }
6473
6474 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
6475 canonProtocols, isKindOf);
6476
6477 // Regenerate Token.
6478 ObjCObjectTypes.lookup(ID, Token);
6479 }
6480
6481 unsigned size = sizeof(ObjCObjectTypeImpl);
6482 size += typeArgs.size() * sizeof(QualType);
6483 size += protocols.size() * sizeof(ObjCProtocolDecl *);
6484 void *mem = Allocate(size, alignof(ObjCObjectTypeImpl));
6485 auto *T =
6486 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
6487 isKindOf);
6488
6489 Types.push_back(T);
6490 ObjCObjectTypes.insert(T, Token);
6491 return QualType(T, 0);
6492}
6493
6494/// Apply Objective-C protocol qualifiers to the given type.
6495/// If this is for the canonical type of a type parameter, we can apply
6496/// protocol qualifiers on the ObjCObjectPointerType.
6499 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
6500 bool allowOnPointerType) const {
6501 hasError = false;
6502
6503 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
6504 return getObjCTypeParamType(objT->getDecl(), protocols);
6505 }
6506
6507 // Apply protocol qualifiers to ObjCObjectPointerType.
6508 if (allowOnPointerType) {
6509 if (const auto *objPtr =
6510 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
6511 const ObjCObjectType *objT = objPtr->getObjectType();
6512 // Merge protocol lists and construct ObjCObjectType.
6514 protocolsVec.append(objT->qual_begin(),
6515 objT->qual_end());
6516 protocolsVec.append(protocols.begin(), protocols.end());
6517 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
6519 objT->getBaseType(),
6520 objT->getTypeArgsAsWritten(),
6521 protocols,
6522 objT->isKindOfTypeAsWritten());
6524 }
6525 }
6526
6527 // Apply protocol qualifiers to ObjCObjectType.
6528 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
6529 // FIXME: Check for protocols to which the class type is already
6530 // known to conform.
6531
6532 return getObjCObjectType(objT->getBaseType(),
6533 objT->getTypeArgsAsWritten(),
6534 protocols,
6535 objT->isKindOfTypeAsWritten());
6536 }
6537
6538 // If the canonical type is ObjCObjectType, ...
6539 if (type->isObjCObjectType()) {
6540 // Silently overwrite any existing protocol qualifiers.
6541 // TODO: determine whether that's the right thing to do.
6542
6543 // FIXME: Check for protocols to which the class type is already
6544 // known to conform.
6545 return getObjCObjectType(type, {}, protocols, false);
6546 }
6547
6548 // id<protocol-list>
6549 if (type->isObjCIdType()) {
6550 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6551 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
6552 objPtr->isKindOfType());
6554 }
6555
6556 // Class<protocol-list>
6557 if (type->isObjCClassType()) {
6558 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6559 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
6560 objPtr->isKindOfType());
6562 }
6563
6564 hasError = true;
6565 return type;
6566}
6567
6570 ArrayRef<ObjCProtocolDecl *> protocols) const {
6571 // We canonicalize to the underlying type.
6572 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
6573 if (!protocols.empty()) {
6574 // Apply the protocol qualifers.
6575 bool hasError;
6577 Canonical, protocols, hasError, true /*allowOnPointerType*/));
6578 assert(!hasError && "Error when apply protocol qualifier to bound type");
6579 }
6580
6581 // Key on the canonical type the node is constructed with, which is what
6582 // Profile() reports; the decl's underlying type can be updated later.
6583 auto Key = std::make_tuple(Decl, Canonical, protocols);
6584 llvm::FoldingSetInsertToken Token;
6585 if (ObjCTypeParamType *TypeParam = ObjCTypeParamTypes.lookup(Key, Token))
6586 return QualType(TypeParam, 0);
6587
6588 unsigned size = sizeof(ObjCTypeParamType);
6589 size += protocols.size() * sizeof(ObjCProtocolDecl *);
6590 void *mem = Allocate(size, alignof(ObjCTypeParamType));
6591 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
6592
6593 Types.push_back(newType);
6594 ObjCTypeParamTypes.insert(newType, Token);
6595 return QualType(newType, 0);
6596}
6597
6599 ObjCTypeParamDecl *New) const {
6600 New->setTypeSourceInfo(getTrivialTypeSourceInfo(Orig->getUnderlyingType()));
6601 // Update TypeForDecl after updating TypeSourceInfo.
6602 auto *NewTypeParamTy = cast<ObjCTypeParamType>(New->TypeForDecl);
6604 protocols.append(NewTypeParamTy->qual_begin(), NewTypeParamTy->qual_end());
6605 QualType UpdatedTy = getObjCTypeParamType(New, protocols);
6606 New->TypeForDecl = UpdatedTy.getTypePtr();
6607}
6608
6609/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
6610/// protocol list adopt all protocols in QT's qualified-id protocol
6611/// list.
6613 ObjCInterfaceDecl *IC) {
6614 if (!QT->isObjCQualifiedIdType())
6615 return false;
6616
6617 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
6618 // If both the right and left sides have qualifiers.
6619 for (auto *Proto : OPT->quals()) {
6620 if (!IC->ClassImplementsProtocol(Proto, false))
6621 return false;
6622 }
6623 return true;
6624 }
6625 return false;
6626}
6627
6628/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
6629/// QT's qualified-id protocol list adopt all protocols in IDecl's list
6630/// of protocols.
6632 ObjCInterfaceDecl *IDecl) {
6633 if (!QT->isObjCQualifiedIdType())
6634 return false;
6635 const auto *OPT = QT->getAs<ObjCObjectPointerType>();
6636 if (!OPT)
6637 return false;
6638 if (!IDecl->hasDefinition())
6639 return false;
6641 CollectInheritedProtocols(IDecl, InheritedProtocols);
6642 if (InheritedProtocols.empty())
6643 return false;
6644 // Check that if every protocol in list of id<plist> conforms to a protocol
6645 // of IDecl's, then bridge casting is ok.
6646 bool Conforms = false;
6647 for (auto *Proto : OPT->quals()) {
6648 Conforms = false;
6649 for (auto *PI : InheritedProtocols) {
6650 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
6651 Conforms = true;
6652 break;
6653 }
6654 }
6655 if (!Conforms)
6656 break;
6657 }
6658 if (Conforms)
6659 return true;
6660
6661 for (auto *PI : InheritedProtocols) {
6662 // If both the right and left sides have qualifiers.
6663 bool Adopts = false;
6664 for (auto *Proto : OPT->quals()) {
6665 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
6666 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
6667 break;
6668 }
6669 if (!Adopts)
6670 return false;
6671 }
6672 return true;
6673}
6674
6675/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
6676/// the given object type.
6678 llvm::FoldingSetInsertToken Token;
6679 if (ObjCObjectPointerType *QT = ObjCObjectPointerTypes.lookup(ObjectT, Token))
6680 return QualType(QT, 0);
6681
6682 // Find the canonical object type.
6683 QualType Canonical;
6684 if (!ObjectT.isCanonical())
6685 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
6686
6687 // No match.
6688 void *Mem =
6690 auto *QType =
6691 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
6692
6693 Types.push_back(QType);
6694 ObjCObjectPointerTypes.insert(QType, Token);
6695 return QualType(QType, 0);
6696}
6697
6698/// getObjCInterfaceType - Return the unique reference to the type for the
6699/// specified ObjC interface decl. The list of protocols is optional.
6701 ObjCInterfaceDecl *PrevDecl) const {
6702 if (Decl->TypeForDecl)
6703 return QualType(Decl->TypeForDecl, 0);
6704
6705 if (PrevDecl) {
6706 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
6707 Decl->TypeForDecl = PrevDecl->TypeForDecl;
6708 return QualType(PrevDecl->TypeForDecl, 0);
6709 }
6710
6711 // Prefer the definition, if there is one.
6712 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
6713 Decl = Def;
6714
6715 void *Mem = Allocate(sizeof(ObjCInterfaceType), alignof(ObjCInterfaceType));
6716 auto *T = new (Mem) ObjCInterfaceType(Decl);
6717 Decl->TypeForDecl = T;
6718 Types.push_back(T);
6719 return QualType(T, 0);
6720}
6721
6722/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
6723/// TypeOfExprType AST's (since expression's are never shared). For example,
6724/// multiple declarations that refer to "typeof(x)" all contain different
6725/// DeclRefExpr's. This doesn't effect the type checker, since it operates
6726/// on canonical type's (which are always unique).
6728 TypeOfExprType *toe;
6729 if (tofExpr->isTypeDependent()) {
6730 llvm::FoldingSetNodeID ID;
6731 DependentTypeOfExprType::Profile(ID, *this, tofExpr,
6732 Kind == TypeOfKind::Unqualified);
6733
6734 llvm::FoldingSetInsertToken Token;
6735 DependentTypeOfExprType *Canon = DependentTypeOfExprTypes.lookup(ID, Token);
6736 if (Canon) {
6737 // We already have a "canonical" version of an identical, dependent
6738 // typeof(expr) type. Use that as our canonical type.
6739 toe = new (*this, alignof(TypeOfExprType)) TypeOfExprType(
6740 *this, tofExpr, Kind, QualType((TypeOfExprType *)Canon, 0));
6741 } else {
6742 // Build a new, canonical typeof(expr) type.
6743 Canon = new (*this, alignof(DependentTypeOfExprType))
6744 DependentTypeOfExprType(*this, tofExpr, Kind);
6745 DependentTypeOfExprTypes.insert(Canon, Token);
6746 toe = Canon;
6747 }
6748 } else {
6749 QualType Canonical = getCanonicalType(tofExpr->getType());
6750 toe = new (*this, alignof(TypeOfExprType))
6751 TypeOfExprType(*this, tofExpr, Kind, Canonical);
6752 }
6753 Types.push_back(toe);
6754 return QualType(toe, 0);
6755}
6756
6757/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
6758/// TypeOfType nodes. The only motivation to unique these nodes would be
6759/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
6760/// an issue. This doesn't affect the type checker, since it operates
6761/// on canonical types (which are always unique).
6763 QualType Canonical = getCanonicalType(tofType);
6764 auto *tot = new (*this, alignof(TypeOfType))
6765 TypeOfType(*this, tofType, Canonical, Kind);
6766 Types.push_back(tot);
6767 return QualType(tot, 0);
6768}
6769
6770/// getReferenceQualifiedType - Given an expr, will return the type for
6771/// that expression, as in [dcl.type.simple]p4 but without taking id-expressions
6772/// and class member access into account.
6774 // C++11 [dcl.type.simple]p4:
6775 // [...]
6776 QualType T = E->getType();
6777 switch (E->getValueKind()) {
6778 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
6779 // type of e;
6780 case VK_XValue:
6781 return getRValueReferenceType(T);
6782 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
6783 // type of e;
6784 case VK_LValue:
6785 return getLValueReferenceType(T);
6786 // - otherwise, decltype(e) is the type of e.
6787 case VK_PRValue:
6788 return T;
6789 }
6790 llvm_unreachable("Unknown value kind");
6791}
6792
6793/// Unlike many "get<Type>" functions, we don't unique DecltypeType
6794/// nodes. This would never be helpful, since each such type has its own
6795/// expression, and would not give a significant memory saving, since there
6796/// is an Expr tree under each such type.
6798 // C++11 [temp.type]p2:
6799 // If an expression e involves a template parameter, decltype(e) denotes a
6800 // unique dependent type. Two such decltype-specifiers refer to the same
6801 // type only if their expressions are equivalent (14.5.6.1).
6802 QualType CanonType;
6803 if (!E->isInstantiationDependent()) {
6804 CanonType = getCanonicalType(UnderlyingType);
6805 } else if (!UnderlyingType.isNull()) {
6806 CanonType = getDecltypeType(E, QualType());
6807 } else {
6808 llvm::FoldingSetNodeID ID;
6809 DependentDecltypeType::Profile(ID, *this, E);
6810
6811 llvm::FoldingSetInsertToken Token;
6812 if (DependentDecltypeType *Canon = DependentDecltypeTypes.lookup(ID, Token))
6813 return QualType(Canon, 0);
6814
6815 // Build a new, canonical decltype(expr) type.
6816 auto *DT =
6817 new (*this, alignof(DependentDecltypeType)) DependentDecltypeType(E);
6818 DependentDecltypeTypes.insert(DT, Token);
6819 Types.push_back(DT);
6820 return QualType(DT, 0);
6821 }
6822 auto *DT = new (*this, alignof(DecltypeType))
6823 DecltypeType(E, UnderlyingType, CanonType);
6824 Types.push_back(DT);
6825 return QualType(DT, 0);
6826}
6827
6829 bool FullySubstituted,
6830 ArrayRef<QualType> Expansions,
6831 UnsignedOrNone Index) const {
6832 QualType Canonical;
6833 if (FullySubstituted && Index) {
6834 Canonical = getCanonicalType(Expansions[*Index]);
6835 } else {
6836 llvm::FoldingSetNodeID ID;
6837 PackIndexingType::Profile(ID, *this, Pattern.getCanonicalType(), IndexExpr,
6838 FullySubstituted, Expansions);
6839 llvm::FoldingSetInsertToken Token;
6840 PackIndexingType *Canon = DependentPackIndexingTypes.lookup(ID, Token);
6841 if (!Canon) {
6842 void *Mem = Allocate(
6843 PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
6845 Canon =
6846 new (Mem) PackIndexingType(QualType(), Pattern.getCanonicalType(),
6847 IndexExpr, FullySubstituted, Expansions);
6848 DependentPackIndexingTypes.insert(Canon, Token);
6849 }
6850 Canonical = QualType(Canon, 0);
6851 }
6852
6853 void *Mem =
6854 Allocate(PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
6856 auto *T = new (Mem) PackIndexingType(Canonical, Pattern, IndexExpr,
6857 FullySubstituted, Expansions);
6858 Types.push_back(T);
6859 return QualType(T, 0);
6860}
6861
6862/// getUnaryTransformationType - We don't unique these, since the memory
6863/// savings are minimal and these are rare.
6866 UnaryTransformType::UTTKind Kind) const {
6867 // Clear UnderlyingType for a dependent base before building the ID: that is
6868 // what the node is constructed with, and what Profile() reports.
6869 if (BaseType->isDependentType()) {
6870 assert(UnderlyingType.isNull() || BaseType == UnderlyingType);
6871 UnderlyingType = QualType();
6872 }
6873
6874 auto Key = std::make_tuple(BaseType, UnderlyingType, Kind);
6875
6876 llvm::FoldingSetInsertToken Token;
6877 if (UnaryTransformType *UT = UnaryTransformTypes.lookup(Key, Token))
6878 return QualType(UT, 0);
6879
6880 QualType CanonType;
6881 if (!BaseType->isDependentType()) {
6882 CanonType = UnderlyingType.getCanonicalType();
6883 } else {
6884 if (QualType CanonBase = BaseType.getCanonicalType();
6885 BaseType != CanonBase) {
6886 CanonType = getUnaryTransformType(CanonBase, QualType(), Kind);
6887 assert(CanonType.isCanonical());
6888 }
6889 }
6890
6891 auto *UT = new (*this, alignof(UnaryTransformType))
6892 UnaryTransformType(BaseType, UnderlyingType, Kind, CanonType);
6893 UnaryTransformTypes.insert(UT, Token);
6894 Types.push_back(UT);
6895 return QualType(UT, 0);
6896}
6897
6898/// getAutoType - Return the uniqued reference to the 'auto' type which has been
6899/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
6900/// canonical deduced-but-dependent 'auto' type.
6904 TemplateName TypeConstraintConcept,
6905 ArrayRef<TemplateArgument> TypeConstraintArgs) const {
6907 TypeConstraintConcept.isNull()) {
6908 assert(DeducedAsType.isNull() && "");
6909 assert(TypeConstraintArgs.empty() && "");
6910 return getAutoDeductType();
6911 }
6912
6913 // Look in the folding set for an existing type.
6914 llvm::FoldingSetNodeID ID;
6915 AutoType::Profile(ID, *this, DK, DeducedAsType, Keyword,
6916 TypeConstraintConcept, TypeConstraintArgs);
6917 if (auto const AT_iter = AutoTypes.find_as(ID); AT_iter != AutoTypes.end())
6918 return QualType(AT_iter->getSecond(), 0);
6919
6920 if (DK == DeducedKind::Deduced) {
6921 assert(!DeducedAsType.isNull() && "deduced type must be provided");
6922 } else {
6923 assert(DeducedAsType.isNull() && "deduced type must not be provided");
6924 if (!TypeConstraintConcept.isNull()) {
6925 bool AnyNonCanonArgs = false;
6926 TemplateName CanonicalConcept =
6927 getCanonicalTemplateName(TypeConstraintConcept);
6928 auto CanonicalConceptArgs = ::getCanonicalTemplateArguments(
6929 *this, TypeConstraintArgs, AnyNonCanonArgs);
6930 if (TypeConstraintConcept != CanonicalConcept || AnyNonCanonArgs)
6931 DeducedAsType = getAutoType(DK, QualType(), Keyword, CanonicalConcept,
6932 CanonicalConceptArgs);
6933 }
6934 }
6935
6936 void *Mem = Allocate(sizeof(AutoType) +
6937 sizeof(TemplateArgument) * TypeConstraintArgs.size(),
6938 alignof(AutoType));
6939 auto *AT = new (Mem) AutoType(DK, DeducedAsType, Keyword,
6940 TypeConstraintConcept, TypeConstraintArgs);
6941#ifndef NDEBUG
6942 llvm::FoldingSetNodeID InsertedID;
6943 AT->Profile(InsertedID, *this);
6944 assert(InsertedID == ID && "ID does not match");
6945#endif
6946 Types.push_back(AT);
6947 AutoTypes.try_emplace(ID.Intern(BumpAlloc), AT);
6948 return QualType(AT, 0);
6949}
6950
6952 QualType CanonT = T.getNonPackExpansionType().getCanonicalType();
6953
6954 // Remove a type-constraint from a top-level auto or decltype(auto).
6955 if (auto *AT = CanonT->getAs<AutoType>()) {
6956 if (!AT->isConstrained())
6957 return T;
6958 return getQualifiedType(
6959 getAutoType(AT->getDeducedKind(), QualType(), AT->getKeyword()),
6960 T.getQualifiers());
6961 }
6962
6963 // FIXME: We only support constrained auto at the top level in the type of a
6964 // non-type template parameter at the moment. Once we lift that restriction,
6965 // we'll need to recursively build types containing auto here.
6966 assert(!CanonT->getContainedAutoType() ||
6967 !CanonT->getContainedAutoType()->isConstrained());
6968 return T;
6969}
6970
6971/// Return the uniqued reference to the deduced template specialization type
6972/// which has been deduced to the given type, or to the canonical undeduced
6973/// such type, or the canonical deduced-but-dependent such type.
6976 TemplateName Template) const {
6977 // Look in the folding set for an existing type.
6978 llvm::FoldingSetInsertToken Token;
6979 llvm::FoldingSetNodeID ID;
6980 DeducedTemplateSpecializationType::Profile(ID, DK, DeducedAsType, Keyword,
6981 Template);
6982 if (DeducedTemplateSpecializationType *DTST =
6983 DeducedTemplateSpecializationTypes.lookup(ID, Token))
6984 return QualType(DTST, 0);
6985
6986 if (DK == DeducedKind::Deduced) {
6987 assert(!DeducedAsType.isNull() && "deduced type must be provided");
6988 } else {
6989 assert(DeducedAsType.isNull() && "deduced type must not be provided");
6990 TemplateName CanonTemplateName = getCanonicalTemplateName(Template);
6991 // FIXME: Can this be formed from a DependentTemplateName, such that the
6992 // keyword should be part of the canonical type?
6994 Template != CanonTemplateName) {
6996 DK, QualType(), ElaboratedTypeKeyword::None, CanonTemplateName);
6997 // Find the insertion position again.
6998 [[maybe_unused]] DeducedTemplateSpecializationType *DTST =
6999 DeducedTemplateSpecializationTypes.lookup(ID, Token);
7000 assert(!DTST && "broken canonicalization");
7001 }
7002 }
7003
7004 auto *DTST = new (*this, alignof(DeducedTemplateSpecializationType))
7005 DeducedTemplateSpecializationType(DK, DeducedAsType, Keyword, Template);
7006
7007#ifndef NDEBUG
7008 llvm::FoldingSetNodeID TempID;
7009 DTST->Profile(TempID);
7010 assert(ID == TempID && "ID does not match");
7011#endif
7012 Types.push_back(DTST);
7013 DeducedTemplateSpecializationTypes.insert(DTST, Token);
7014 return QualType(DTST, 0);
7015}
7016
7017/// getAtomicType - Return the uniqued reference to the atomic type for
7018/// the given value type.
7020 // Unique pointers, to guarantee there is only one pointer of a particular
7021 // structure.
7022 llvm::FoldingSetInsertToken Token;
7023 if (AtomicType *AT = AtomicTypes.lookup(T, Token))
7024 return QualType(AT, 0);
7025
7026 // If the atomic value type isn't canonical, this won't be a canonical type
7027 // either, so fill in the canonical type field.
7028 QualType Canonical;
7029 if (!T.isCanonical()) {
7030 Canonical = getAtomicType(getCanonicalType(T));
7031
7032 assert(!AtomicTypes.lookup(T, Token) && "Shouldn't be in the map!");
7033 }
7034 auto *New = new (*this, alignof(AtomicType)) AtomicType(T, Canonical);
7035 Types.push_back(New);
7036 AtomicTypes.insert(New, Token);
7037 return QualType(New, 0);
7038}
7039
7040/// getAutoDeductType - Get type pattern for deducing against 'auto'.
7042 if (AutoDeductTy.isNull())
7044 new (*this, alignof(AutoType))
7046 /*TypeConstraintConcept=*/TemplateName(),
7047 /*TypeConstraintArgs=*/{}),
7048 0);
7049 return AutoDeductTy;
7050}
7051
7052/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
7054 if (AutoRRefDeductTy.isNull())
7056 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
7057 return AutoRRefDeductTy;
7058}
7059
7060/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
7061/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
7062/// needs to agree with the definition in <stddef.h>.
7066
7068 return getFromTargetType(Target->getSizeType());
7069}
7070
7071/// Return the unique signed counterpart of the integer type
7072/// corresponding to size_t.
7076
7077/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
7078/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
7082
7083/// Return the unique unsigned counterpart of "ptrdiff_t"
7084/// integer type. The standard (C11 7.21.6.1p7) refers to this type
7085/// in the definition of %tu format specifier.
7087 return getFromTargetType(Target->getUnsignedPtrDiffType(LangAS::Default));
7088}
7089
7090/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
7092 return getFromTargetType(Target->getIntMaxType());
7093}
7094
7095/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
7097 return getFromTargetType(Target->getUIntMaxType());
7098}
7099
7100/// getSignedWCharType - Return the type of "signed wchar_t".
7101/// Used when in C++, as a GCC extension.
7103 // FIXME: derive from "Target" ?
7104 return WCharTy;
7105}
7106
7107/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
7108/// Used when in C++, as a GCC extension.
7110 // FIXME: derive from "Target" ?
7111 return UnsignedIntTy;
7112}
7113
7115 return getFromTargetType(Target->getIntPtrType());
7116}
7117
7121
7122/// Return the unique type for "pid_t" defined in
7123/// <sys/types.h>. We need this to compute the correct type for vfork().
7125 return getFromTargetType(Target->getProcessIDType());
7126}
7127
7128//===----------------------------------------------------------------------===//
7129// Type Operators
7130//===----------------------------------------------------------------------===//
7131
7133 // Push qualifiers into arrays, and then discard any remaining
7134 // qualifiers.
7135 T = getCanonicalType(T);
7137 const Type *Ty = T.getTypePtr();
7141 } else if (isa<ArrayType>(Ty)) {
7143 } else if (isa<FunctionType>(Ty)) {
7144 Result = getPointerType(QualType(Ty, 0));
7145 } else {
7146 Result = QualType(Ty, 0);
7147 }
7148
7150}
7151
7153 Qualifiers &quals) const {
7154 SplitQualType splitType = type.getSplitUnqualifiedType();
7155
7156 // FIXME: getSplitUnqualifiedType() actually walks all the way to
7157 // the unqualified desugared type and then drops it on the floor.
7158 // We then have to strip that sugar back off with
7159 // getUnqualifiedDesugaredType(), which is silly.
7160 const auto *AT =
7161 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
7162
7163 // If we don't have an array, just use the results in splitType.
7164 if (!AT) {
7165 quals = splitType.Quals;
7166 return QualType(splitType.Ty, 0);
7167 }
7168
7169 // Otherwise, recurse on the array's element type.
7170 QualType elementType = AT->getElementType();
7171 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
7172
7173 // If that didn't change the element type, AT has no qualifiers, so we
7174 // can just use the results in splitType.
7175 if (elementType == unqualElementType) {
7176 assert(quals.empty()); // from the recursive call
7177 quals = splitType.Quals;
7178 return QualType(splitType.Ty, 0);
7179 }
7180
7181 // Otherwise, add in the qualifiers from the outermost type, then
7182 // build the type back up.
7183 quals.addConsistentQualifiers(splitType.Quals);
7184
7185 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
7186 return getConstantArrayType(unqualElementType, CAT->getSize(),
7187 CAT->getSizeExpr(), CAT->getSizeModifier(), 0);
7188 }
7189
7190 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
7191 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
7192 }
7193
7194 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
7195 return getVariableArrayType(unqualElementType, VAT->getSizeExpr(),
7196 VAT->getSizeModifier(),
7197 VAT->getIndexTypeCVRQualifiers());
7198 }
7199
7200 const auto *DSAT = cast<DependentSizedArrayType>(AT);
7201 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
7202 DSAT->getSizeModifier(), 0);
7203}
7204
7205/// Attempt to unwrap two types that may both be array types with the same bound
7206/// (or both be array types of unknown bound) for the purpose of comparing the
7207/// cv-decomposition of two types per C++ [conv.qual].
7208///
7209/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
7210/// C++20 [conv.qual], if permitted by the current language mode.
7212 bool AllowPiMismatch) const {
7213 while (true) {
7214 auto *AT1 = getAsArrayType(T1);
7215 if (!AT1)
7216 return;
7217
7218 auto *AT2 = getAsArrayType(T2);
7219 if (!AT2)
7220 return;
7221
7222 // If we don't have two array types with the same constant bound nor two
7223 // incomplete array types, we've unwrapped everything we can.
7224 // C++20 also permits one type to be a constant array type and the other
7225 // to be an incomplete array type.
7226 // FIXME: Consider also unwrapping array of unknown bound and VLA.
7227 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
7228 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
7229 if (!((CAT2 && CAT1->getSize() == CAT2->getSize()) ||
7230 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
7232 return;
7233 } else if (isa<IncompleteArrayType>(AT1)) {
7234 if (!(isa<IncompleteArrayType>(AT2) ||
7235 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
7237 return;
7238 } else {
7239 return;
7240 }
7241
7242 T1 = AT1->getElementType();
7243 T2 = AT2->getElementType();
7244 }
7245}
7246
7247/// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
7248///
7249/// If T1 and T2 are both pointer types of the same kind, or both array types
7250/// with the same bound, unwraps layers from T1 and T2 until a pointer type is
7251/// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
7252///
7253/// This function will typically be called in a loop that successively
7254/// "unwraps" pointer and pointer-to-member types to compare them at each
7255/// level.
7256///
7257/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
7258/// C++20 [conv.qual], if permitted by the current language mode.
7259///
7260/// \return \c true if a pointer type was unwrapped, \c false if we reached a
7261/// pair of types that can't be unwrapped further.
7263 bool AllowPiMismatch) const {
7264 UnwrapSimilarArrayTypes(T1, T2, AllowPiMismatch);
7265
7266 const auto *T1PtrType = T1->getAs<PointerType>();
7267 const auto *T2PtrType = T2->getAs<PointerType>();
7268 if (T1PtrType && T2PtrType) {
7269 T1 = T1PtrType->getPointeeType();
7270 T2 = T2PtrType->getPointeeType();
7271 return true;
7272 }
7273
7274 if (const auto *T1MPType = T1->getAsCanonical<MemberPointerType>(),
7275 *T2MPType = T2->getAsCanonical<MemberPointerType>();
7276 T1MPType && T2MPType) {
7277 // Compare the qualifiers of the canonical type, as the non-canonical type
7278 // may have qualifiers pointing to a base or derived class.
7279 if (T1MPType->getQualifier() != T2MPType->getQualifier())
7280 return false;
7281 // Get the pointee types of the non-canonical type, in order to preserve
7282 // their sugar.
7283 T1 = T1->getAs<MemberPointerType>()->getPointeeType();
7284 T2 = T2->getAs<MemberPointerType>()->getPointeeType();
7285 return true;
7286 }
7287
7288 if (getLangOpts().ObjC) {
7289 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
7290 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
7291 if (T1OPType && T2OPType) {
7292 T1 = T1OPType->getPointeeType();
7293 T2 = T2OPType->getPointeeType();
7294 return true;
7295 }
7296 }
7297
7298 // FIXME: Block pointers, too?
7299
7300 return false;
7301}
7302
7304 while (true) {
7305 Qualifiers Quals;
7306 T1 = getUnqualifiedArrayType(T1, Quals);
7307 T2 = getUnqualifiedArrayType(T2, Quals);
7308 if (hasSameType(T1, T2))
7309 return true;
7310 if (!UnwrapSimilarTypes(T1, T2))
7311 return false;
7312 }
7313}
7314
7316 while (true) {
7317 Qualifiers Quals1, Quals2;
7318 T1 = getUnqualifiedArrayType(T1, Quals1);
7319 T2 = getUnqualifiedArrayType(T2, Quals2);
7320
7321 Quals1.removeCVRQualifiers();
7322 Quals2.removeCVRQualifiers();
7323 if (Quals1 != Quals2)
7324 return false;
7325
7326 if (hasSameType(T1, T2))
7327 return true;
7328
7329 if (!UnwrapSimilarTypes(T1, T2, /*AllowPiMismatch*/ false))
7330 return false;
7331 }
7332}
7333
7336 SourceLocation NameLoc) const {
7337 switch (Name.getKind()) {
7340 // DNInfo work in progress: CHECKME: what about DNLoc?
7342 NameLoc);
7343
7346 // DNInfo work in progress: CHECKME: what about DNLoc?
7347 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
7348 }
7349
7352 return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
7353 }
7354
7358 DeclarationName DName;
7359 if (const IdentifierInfo *II = TN.getIdentifier()) {
7360 DName = DeclarationNames.getIdentifier(II);
7361 return DeclarationNameInfo(DName, NameLoc);
7362 } else {
7363 DName = DeclarationNames.getCXXOperatorName(TN.getOperator());
7364 // DNInfo work in progress: FIXME: source locations?
7365 DeclarationNameLoc DNLoc =
7367 return DeclarationNameInfo(DName, NameLoc, DNLoc);
7368 }
7369 }
7370
7374 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
7375 NameLoc);
7376 }
7377
7382 NameLoc);
7383 }
7386 NameLoc);
7389 return getNameForTemplate(DTS->getUnderlying(), NameLoc);
7390 }
7393 return getNameForTemplate(PI->getPattern(), NameLoc);
7394 }
7395 }
7396
7397 llvm_unreachable("bad template name kind!");
7398}
7399
7400const TemplateArgument *
7402 auto handleParam = [](auto *TP) -> const TemplateArgument * {
7403 if (!TP->hasDefaultArgument())
7404 return nullptr;
7405 return &TP->getDefaultArgument().getArgument();
7406 };
7407 switch (P->getKind()) {
7408 case NamedDecl::TemplateTypeParm:
7409 return handleParam(cast<TemplateTypeParmDecl>(P));
7410 case NamedDecl::NonTypeTemplateParm:
7411 return handleParam(cast<NonTypeTemplateParmDecl>(P));
7412 case NamedDecl::TemplateTemplateParm:
7413 return handleParam(cast<TemplateTemplateParmDecl>(P));
7414 default:
7415 llvm_unreachable("Unexpected template parameter kind");
7416 }
7417}
7418
7420 bool IgnoreDeduced) const {
7421 while (std::optional<TemplateName> UnderlyingOrNone =
7422 Name.desugar(IgnoreDeduced))
7423 Name = *UnderlyingOrNone;
7424
7425 switch (Name.getKind()) {
7428 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template))
7430
7431 // The canonical template name is the canonical template declaration.
7432 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
7433 }
7434
7436 // An assumed template is just a name, so it is already canonical.
7437 return Name;
7438
7440 llvm_unreachable("cannot canonicalize overloaded template");
7441
7444 assert(DTN && "Non-dependent template names must refer to template decls.");
7445 NestedNameSpecifier Qualifier = DTN->getQualifier();
7446 NestedNameSpecifier CanonQualifier = Qualifier.getCanonical();
7447 if (Qualifier != CanonQualifier || !DTN->hasTemplateKeyword())
7448 return getDependentTemplateName({CanonQualifier, DTN->getName(),
7449 /*HasTemplateKeyword=*/true});
7450 return Name;
7451 }
7452
7456 TemplateArgument canonArgPack =
7459 canonArgPack, subst->getAssociatedDecl()->getCanonicalDecl(),
7460 subst->getIndex(), subst->getFinal());
7461 }
7462
7465 SmallVector<TemplateName, 4> CanonExpansions;
7466 for (TemplateName T : PI->getExpansions())
7467 CanonExpansions.push_back(getCanonicalTemplateName(T, IgnoreDeduced));
7469 getCanonicalTemplateName(PI->getPattern(), IgnoreDeduced),
7470 PI->getIndexExpr(), PI->isFullySubstituted(), CanonExpansions);
7471 }
7473 assert(IgnoreDeduced == false);
7475 DefaultArguments DefArgs = DTS->getDefaultArguments();
7476 TemplateName Underlying = DTS->getUnderlying();
7477
7478 TemplateName CanonUnderlying =
7479 getCanonicalTemplateName(Underlying, /*IgnoreDeduced=*/true);
7480 bool NonCanonical = CanonUnderlying != Underlying;
7481 auto CanonArgs =
7482 getCanonicalTemplateArguments(*this, DefArgs.Args, NonCanonical);
7483
7484 ArrayRef<NamedDecl *> Params =
7485 CanonUnderlying.getAsTemplateDecl()->getTemplateParameters()->asArray();
7486 assert(CanonArgs.size() <= Params.size());
7487 // A deduced template name which deduces the same default arguments already
7488 // declared in the underlying template is the same template as the
7489 // underlying template. We need need to note any arguments which differ from
7490 // the corresponding declaration. If any argument differs, we must build a
7491 // deduced template name.
7492 for (int I = CanonArgs.size() - 1; I >= 0; --I) {
7494 if (!A)
7495 break;
7496 auto CanonParamDefArg = getCanonicalTemplateArgument(*A);
7497 TemplateArgument &CanonDefArg = CanonArgs[I];
7498 if (CanonDefArg.structurallyEquals(CanonParamDefArg))
7499 continue;
7500 // Keep popping from the back any deault arguments which are the same.
7501 if (I == int(CanonArgs.size() - 1))
7502 CanonArgs.pop_back();
7503 NonCanonical = true;
7504 }
7505 return NonCanonical ? getDeducedTemplateName(
7506 CanonUnderlying,
7507 /*DefaultArgs=*/{DefArgs.StartPos, CanonArgs})
7508 : Name;
7509 }
7513 llvm_unreachable("always sugar node");
7514 }
7515
7516 llvm_unreachable("bad template name!");
7517}
7518
7520 const TemplateName &Y,
7521 bool IgnoreDeduced) const {
7522 return getCanonicalTemplateName(X, IgnoreDeduced) ==
7523 getCanonicalTemplateName(Y, IgnoreDeduced);
7524}
7525
7527 const AssociatedConstraint &ACX, const AssociatedConstraint &ACY) const {
7528 if (ACX.ArgPackSubstIndex != ACY.ArgPackSubstIndex)
7529 return false;
7531 return false;
7532 return true;
7533}
7534
7535bool ASTContext::isSameConstraintExpr(const Expr *XCE, const Expr *YCE) const {
7536 if (!XCE != !YCE)
7537 return false;
7538
7539 if (!XCE)
7540 return true;
7541
7542 llvm::FoldingSetNodeID XCEID, YCEID;
7543 XCE->Profile(XCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7544 YCE->Profile(YCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7545 return XCEID == YCEID;
7546}
7547
7549 const TypeConstraint *YTC) const {
7550 if (!XTC != !YTC)
7551 return false;
7552
7553 if (!XTC)
7554 return true;
7555
7558 if (!NCX || !NCY || !isSameEntity(NCX, NCY))
7559 return false;
7562 return false;
7564 if (XTC->getConceptReference()
7566 ->NumTemplateArgs !=
7568 return false;
7569
7570 // Compare slowly by profiling.
7571 //
7572 // We couldn't compare the profiling result for the template
7573 // args here. Consider the following example in different modules:
7574 //
7575 // template <__integer_like _Tp, C<_Tp> Sentinel>
7576 // constexpr _Tp operator()(_Tp &&__t, Sentinel &&last) const {
7577 // return __t;
7578 // }
7579 //
7580 // When we compare the profiling result for `C<_Tp>` in different
7581 // modules, it will compare the type of `_Tp` in different modules.
7582 // However, the type of `_Tp` in different modules refer to different
7583 // types here naturally. So we couldn't compare the profiling result
7584 // for the template args directly.
7587}
7588
7590 const NamedDecl *Y) const {
7591 if (X->getKind() != Y->getKind())
7592 return false;
7593
7594 if (auto *TX = dyn_cast<TemplateTypeParmDecl>(X)) {
7595 auto *TY = cast<TemplateTypeParmDecl>(Y);
7596 if (TX->isParameterPack() != TY->isParameterPack())
7597 return false;
7598 if (TX->hasTypeConstraint() != TY->hasTypeConstraint())
7599 return false;
7600 return isSameTypeConstraint(TX->getTypeConstraint(),
7601 TY->getTypeConstraint());
7602 }
7603
7604 if (auto *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
7605 auto *TY = cast<NonTypeTemplateParmDecl>(Y);
7606 return TX->isParameterPack() == TY->isParameterPack() &&
7607 TX->getASTContext().hasSameType(TX->getType(), TY->getType()) &&
7608 isSameConstraintExpr(TX->getPlaceholderTypeConstraint(),
7609 TY->getPlaceholderTypeConstraint());
7610 }
7611
7613 auto *TY = cast<TemplateTemplateParmDecl>(Y);
7614 return TX->isParameterPack() == TY->isParameterPack() &&
7615 isSameTemplateParameterList(TX->getTemplateParameters(),
7616 TY->getTemplateParameters());
7617}
7618
7620 const TemplateParameterList *X, const TemplateParameterList *Y) const {
7621 if (X->size() != Y->size())
7622 return false;
7623
7624 for (unsigned I = 0, N = X->size(); I != N; ++I)
7625 if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I)))
7626 return false;
7627
7628 return isSameConstraintExpr(X->getRequiresClause(), Y->getRequiresClause());
7629}
7630
7632 const NamedDecl *Y) const {
7633 // If the type parameter isn't the same already, we don't need to check the
7634 // default argument further.
7635 if (!isSameTemplateParameter(X, Y))
7636 return false;
7637
7638 if (auto *TTPX = dyn_cast<TemplateTypeParmDecl>(X)) {
7639 auto *TTPY = cast<TemplateTypeParmDecl>(Y);
7640 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7641 return false;
7642
7643 return hasSameType(TTPX->getDefaultArgument().getArgument().getAsType(),
7644 TTPY->getDefaultArgument().getArgument().getAsType());
7645 }
7646
7647 if (auto *NTTPX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
7648 auto *NTTPY = cast<NonTypeTemplateParmDecl>(Y);
7649 if (!NTTPX->hasDefaultArgument() || !NTTPY->hasDefaultArgument())
7650 return false;
7651
7652 Expr *DefaultArgumentX =
7653 NTTPX->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7654 Expr *DefaultArgumentY =
7655 NTTPY->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7656 llvm::FoldingSetNodeID XID, YID;
7657 DefaultArgumentX->Profile(XID, *this, /*Canonical=*/true);
7658 DefaultArgumentY->Profile(YID, *this, /*Canonical=*/true);
7659 return XID == YID;
7660 }
7661
7662 auto *TTPX = cast<TemplateTemplateParmDecl>(X);
7663 auto *TTPY = cast<TemplateTemplateParmDecl>(Y);
7664
7665 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7666 return false;
7667
7668 const TemplateArgument &TAX = TTPX->getDefaultArgument().getArgument();
7669 const TemplateArgument &TAY = TTPY->getDefaultArgument().getArgument();
7670 return hasSameTemplateName(TAX.getAsTemplate(), TAY.getAsTemplate());
7671}
7672
7674 const NestedNameSpecifier Y) {
7675 if (X == Y)
7676 return true;
7677 if (!X || !Y)
7678 return false;
7679
7680 auto Kind = X.getKind();
7681 if (Kind != Y.getKind())
7682 return false;
7683
7684 // FIXME: For namespaces and types, we're permitted to check that the entity
7685 // is named via the same tokens. We should probably do so.
7686 switch (Kind) {
7688 auto [NamespaceX, PrefixX] = X.getAsNamespaceAndPrefix();
7689 auto [NamespaceY, PrefixY] = Y.getAsNamespaceAndPrefix();
7690 if (!declaresSameEntity(NamespaceX->getNamespace(),
7691 NamespaceY->getNamespace()))
7692 return false;
7693 return isSameQualifier(PrefixX, PrefixY);
7694 }
7696 const auto *TX = X.getAsType(), *TY = Y.getAsType();
7697 if (TX->getCanonicalTypeInternal() != TY->getCanonicalTypeInternal())
7698 return false;
7699 return isSameQualifier(TX->getPrefix(), TY->getPrefix());
7700 }
7704 return true;
7705 }
7706 llvm_unreachable("unhandled qualifier kind");
7707}
7708
7709static bool hasSameCudaAttrs(const FunctionDecl *A, const FunctionDecl *B) {
7710 if (!A->getASTContext().getLangOpts().CUDA)
7711 return true; // Target attributes are overloadable in CUDA compilation only.
7712 if (A->hasAttr<CUDADeviceAttr>() != B->hasAttr<CUDADeviceAttr>())
7713 return false;
7714 if (A->hasAttr<CUDADeviceAttr>() && B->hasAttr<CUDADeviceAttr>())
7715 return A->hasAttr<CUDAHostAttr>() == B->hasAttr<CUDAHostAttr>();
7716 return true; // unattributed and __host__ functions are the same.
7717}
7718
7719/// Determine whether the attributes we can overload on are identical for A and
7720/// B. Will ignore any overloadable attrs represented in the type of A and B.
7722 const FunctionDecl *B) {
7723 // Note that pass_object_size attributes are represented in the function's
7724 // ExtParameterInfo, so we don't need to check them here.
7725
7726 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
7727 auto AEnableIfAttrs = A->specific_attrs<EnableIfAttr>();
7728 auto BEnableIfAttrs = B->specific_attrs<EnableIfAttr>();
7729
7730 for (auto Pair : zip_longest(AEnableIfAttrs, BEnableIfAttrs)) {
7731 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
7732 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
7733
7734 // Return false if the number of enable_if attributes is different.
7735 if (!Cand1A || !Cand2A)
7736 return false;
7737
7738 Cand1ID.clear();
7739 Cand2ID.clear();
7740
7741 (*Cand1A)->getCond()->Profile(Cand1ID, A->getASTContext(), true);
7742 (*Cand2A)->getCond()->Profile(Cand2ID, B->getASTContext(), true);
7743
7744 // Return false if any of the enable_if expressions of A and B are
7745 // different.
7746 if (Cand1ID != Cand2ID)
7747 return false;
7748 }
7749 return hasSameCudaAttrs(A, B);
7750}
7751
7752bool ASTContext::isSameEntity(const NamedDecl *X, const NamedDecl *Y) const {
7753 // Caution: this function is called by the AST reader during deserialization,
7754 // so it cannot rely on AST invariants being met. Non-trivial accessors
7755 // should be avoided, along with any traversal of redeclaration chains.
7756
7757 if (X == Y)
7758 return true;
7759
7760 if (X->getDeclName() != Y->getDeclName())
7761 return false;
7762
7763 // Must be in the same context.
7764 //
7765 // Note that we can't use DeclContext::Equals here, because the DeclContexts
7766 // could be two different declarations of the same function. (We will fix the
7767 // semantic DC to refer to the primary definition after merging.)
7768 if (!declaresSameEntity(cast<Decl>(X->getDeclContext()->getRedeclContext()),
7770 return false;
7771
7772 // If either X or Y are local to the owning module, they are only possible to
7773 // be the same entity if they are in the same module.
7774 if (X->isModuleLocal() || Y->isModuleLocal())
7775 if (!isInSameModule(X->getOwningModule(), Y->getOwningModule()))
7776 return false;
7777
7778 // Two typedefs refer to the same entity if they have the same underlying
7779 // type.
7780 if (const auto *TypedefX = dyn_cast<TypedefNameDecl>(X))
7781 if (const auto *TypedefY = dyn_cast<TypedefNameDecl>(Y))
7782 return hasSameType(TypedefX->getUnderlyingType(),
7783 TypedefY->getUnderlyingType());
7784
7785 // Must have the same kind.
7786 if (X->getKind() != Y->getKind())
7787 return false;
7788
7789 // Objective-C classes and protocols with the same name always match.
7791 return true;
7792
7794 // No need to handle these here: we merge them when adding them to the
7795 // template.
7796 return false;
7797 }
7798
7799 // Compatible tags match.
7800 if (const auto *TagX = dyn_cast<TagDecl>(X)) {
7801 const auto *TagY = cast<TagDecl>(Y);
7802 return (TagX->getTagKind() == TagY->getTagKind()) ||
7803 ((TagX->getTagKind() == TagTypeKind::Struct ||
7804 TagX->getTagKind() == TagTypeKind::Class ||
7805 TagX->getTagKind() == TagTypeKind::Interface) &&
7806 (TagY->getTagKind() == TagTypeKind::Struct ||
7807 TagY->getTagKind() == TagTypeKind::Class ||
7808 TagY->getTagKind() == TagTypeKind::Interface));
7809 }
7810
7811 // Functions with the same type and linkage match.
7812 // FIXME: This needs to cope with merging of prototyped/non-prototyped
7813 // functions, etc.
7814 if (const auto *FuncX = dyn_cast<FunctionDecl>(X)) {
7815 const auto *FuncY = cast<FunctionDecl>(Y);
7816 if (const auto *CtorX = dyn_cast<CXXConstructorDecl>(X)) {
7817 const auto *CtorY = cast<CXXConstructorDecl>(Y);
7818 if (CtorX->getInheritedConstructor() &&
7819 !isSameEntity(CtorX->getInheritedConstructor().getConstructor(),
7820 CtorY->getInheritedConstructor().getConstructor()))
7821 return false;
7822 }
7823
7824 if (FuncX->isMultiVersion() != FuncY->isMultiVersion())
7825 return false;
7826
7827 // Multiversioned functions with different feature strings are represented
7828 // as separate declarations.
7829 if (FuncX->isMultiVersion()) {
7830 const auto *TAX = FuncX->getAttr<TargetAttr>();
7831 const auto *TAY = FuncY->getAttr<TargetAttr>();
7832 assert(TAX && TAY && "Multiversion Function without target attribute");
7833
7834 if (TAX->getFeaturesStr() != TAY->getFeaturesStr())
7835 return false;
7836 }
7837
7838 // Per C++20 [temp.over.link]/4, friends in different classes are sometimes
7839 // not the same entity if they are constrained.
7840 if ((FuncX->isMemberLikeConstrainedFriend() ||
7841 FuncY->isMemberLikeConstrainedFriend()) &&
7842 !FuncX->getLexicalDeclContext()->Equals(
7843 FuncY->getLexicalDeclContext())) {
7844 return false;
7845 }
7846
7847 if (!isSameAssociatedConstraint(FuncX->getTrailingRequiresClause(),
7848 FuncY->getTrailingRequiresClause()))
7849 return false;
7850
7851 auto GetTypeAsWritten = [](const FunctionDecl *FD) {
7852 // Map to the first declaration that we've already merged into this one.
7853 // The TSI of redeclarations might not match (due to calling conventions
7854 // being inherited onto the type but not the TSI), but the TSI type of
7855 // the first declaration of the function should match across modules.
7856 FD = FD->getCanonicalDecl();
7857 return FD->getTypeSourceInfo() ? FD->getTypeSourceInfo()->getType()
7858 : FD->getType();
7859 };
7860 QualType XT = GetTypeAsWritten(FuncX), YT = GetTypeAsWritten(FuncY);
7861 if (!hasSameType(XT, YT)) {
7862 // We can get functions with different types on the redecl chain in C++17
7863 // if they have differing exception specifications and at least one of
7864 // the excpetion specs is unresolved.
7865 auto *XFPT = XT->getAs<FunctionProtoType>();
7866 auto *YFPT = YT->getAs<FunctionProtoType>();
7867 if (getLangOpts().CPlusPlus17 && XFPT && YFPT &&
7868 (isUnresolvedExceptionSpec(XFPT->getExceptionSpecType()) ||
7871 return true;
7872 return false;
7873 }
7874
7875 return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() &&
7876 hasSameOverloadableAttrs(FuncX, FuncY);
7877 }
7878
7879 // Variables with the same type and linkage match.
7880 if (const auto *VarX = dyn_cast<VarDecl>(X)) {
7881 const auto *VarY = cast<VarDecl>(Y);
7882 if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) {
7883 // During deserialization, we might compare variables before we load
7884 // their types. Assume the types will end up being the same.
7885 if (VarX->getType().isNull() || VarY->getType().isNull())
7886 return true;
7887
7888 if (hasSameType(VarX->getType(), VarY->getType()))
7889 return true;
7890
7891 // We can get decls with different types on the redecl chain. Eg.
7892 // template <typename T> struct S { static T Var[]; }; // #1
7893 // template <typename T> T S<T>::Var[sizeof(T)]; // #2
7894 // Only? happens when completing an incomplete array type. In this case
7895 // when comparing #1 and #2 we should go through their element type.
7896 const ArrayType *VarXTy = getAsArrayType(VarX->getType());
7897 const ArrayType *VarYTy = getAsArrayType(VarY->getType());
7898 if (!VarXTy || !VarYTy)
7899 return false;
7900 if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType())
7901 return hasSameType(VarXTy->getElementType(), VarYTy->getElementType());
7902 }
7903 return false;
7904 }
7905
7906 // Namespaces with the same name and inlinedness match.
7907 if (const auto *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
7908 const auto *NamespaceY = cast<NamespaceDecl>(Y);
7909 return NamespaceX->isInline() == NamespaceY->isInline();
7910 }
7911
7912 // Identical template names and kinds match if their template parameter lists
7913 // and patterns match.
7914 if (const auto *TemplateX = dyn_cast<TemplateDecl>(X)) {
7915 const auto *TemplateY = cast<TemplateDecl>(Y);
7916
7917 // ConceptDecl wouldn't be the same if their constraint expression differs.
7918 if (const auto *ConceptX = dyn_cast<ConceptDecl>(X)) {
7919 const auto *ConceptY = cast<ConceptDecl>(Y);
7920 if (!isSameConstraintExpr(ConceptX->getConstraintExpr(),
7921 ConceptY->getConstraintExpr()))
7922 return false;
7923 }
7924
7925 return isSameEntity(TemplateX->getTemplatedDecl(),
7926 TemplateY->getTemplatedDecl()) &&
7927 isSameTemplateParameterList(TemplateX->getTemplateParameters(),
7928 TemplateY->getTemplateParameters());
7929 }
7930
7931 // Fields with the same name and the same type match.
7932 if (const auto *FDX = dyn_cast<FieldDecl>(X)) {
7933 const auto *FDY = cast<FieldDecl>(Y);
7934 // FIXME: Also check the bitwidth is odr-equivalent, if any.
7935 return hasSameType(FDX->getType(), FDY->getType());
7936 }
7937
7938 // Indirect fields with the same target field match.
7939 if (const auto *IFDX = dyn_cast<IndirectFieldDecl>(X)) {
7940 const auto *IFDY = cast<IndirectFieldDecl>(Y);
7941 return IFDX->getAnonField()->getCanonicalDecl() ==
7942 IFDY->getAnonField()->getCanonicalDecl();
7943 }
7944
7945 // Enumerators with the same name match.
7947 // FIXME: Also check the value is odr-equivalent.
7948 return true;
7949
7950 // Using shadow declarations with the same target match.
7951 if (const auto *USX = dyn_cast<UsingShadowDecl>(X)) {
7952 const auto *USY = cast<UsingShadowDecl>(Y);
7953 return declaresSameEntity(USX->getTargetDecl(), USY->getTargetDecl());
7954 }
7955
7956 // Using declarations with the same qualifier match. (We already know that
7957 // the name matches.)
7958 if (const auto *UX = dyn_cast<UsingDecl>(X)) {
7959 const auto *UY = cast<UsingDecl>(Y);
7960 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7961 UX->hasTypename() == UY->hasTypename() &&
7962 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7963 }
7964 if (const auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) {
7965 const auto *UY = cast<UnresolvedUsingValueDecl>(Y);
7966 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7967 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7968 }
7969 if (const auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X)) {
7970 return isSameQualifier(
7971 UX->getQualifier(),
7972 cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier());
7973 }
7974
7975 // Using-pack declarations are only created by instantiation, and match if
7976 // they're instantiated from matching UnresolvedUsing...Decls.
7977 if (const auto *UX = dyn_cast<UsingPackDecl>(X)) {
7978 return declaresSameEntity(
7979 UX->getInstantiatedFromUsingDecl(),
7980 cast<UsingPackDecl>(Y)->getInstantiatedFromUsingDecl());
7981 }
7982
7983 // Namespace alias definitions with the same target match.
7984 if (const auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) {
7985 const auto *NAY = cast<NamespaceAliasDecl>(Y);
7986 return NAX->getNamespace()->Equals(NAY->getNamespace());
7987 }
7988
7989 if (const auto *UX = dyn_cast<UsingEnumDecl>(X)) {
7990 const auto *UY = cast<UsingEnumDecl>(Y);
7991 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7992 declaresSameEntity(UX->getEnumDecl(), UY->getEnumDecl());
7993 }
7994
7995 return false;
7996}
7997
8000 switch (Arg.getKind()) {
8002 return Arg;
8003
8005 return TemplateArgument(Arg.getAsExpr(), /*IsCanonical=*/true,
8006 Arg.getIsDefaulted());
8007
8009 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
8011 Arg.getIsDefaulted());
8012 }
8013
8016 /*isNullPtr*/ true, Arg.getIsDefaulted());
8017
8020 Arg.getIsDefaulted());
8021
8023 return TemplateArgument(
8026
8029
8031 return TemplateArgument(*this,
8034
8037 /*isNullPtr*/ false, Arg.getIsDefaulted());
8038
8040 bool AnyNonCanonArgs = false;
8041 auto CanonArgs = ::getCanonicalTemplateArguments(
8042 *this, Arg.pack_elements(), AnyNonCanonArgs);
8043 if (!AnyNonCanonArgs)
8044 return Arg;
8046 const_cast<ASTContext &>(*this), CanonArgs);
8047 NewArg.setIsDefaulted(Arg.getIsDefaulted());
8048 return NewArg;
8049 }
8050 }
8051
8052 // Silence GCC warning
8053 llvm_unreachable("Unhandled template argument kind");
8054}
8055
8057 const TemplateArgument &Arg2) const {
8058 if (Arg1.getKind() != Arg2.getKind())
8059 return false;
8060
8061 switch (Arg1.getKind()) {
8063 llvm_unreachable("Comparing NULL template argument");
8064
8066 return hasSameType(Arg1.getAsType(), Arg2.getAsType());
8067
8069 return Arg1.getAsDecl()->getUnderlyingDecl()->getCanonicalDecl() ==
8071
8073 return hasSameType(Arg1.getNullPtrType(), Arg2.getNullPtrType());
8074
8079
8081 return llvm::APSInt::isSameValue(Arg1.getAsIntegral(),
8082 Arg2.getAsIntegral());
8083
8085 return Arg1.structurallyEquals(Arg2);
8086
8088 llvm::FoldingSetNodeID ID1, ID2;
8089 Arg1.getAsExpr()->Profile(ID1, *this, /*Canonical=*/true);
8090 Arg2.getAsExpr()->Profile(ID2, *this, /*Canonical=*/true);
8091 return ID1 == ID2;
8092 }
8093
8095 return llvm::equal(
8096 Arg1.getPackAsArray(), Arg2.getPackAsArray(),
8097 [&](const TemplateArgument &Arg1, const TemplateArgument &Arg2) {
8098 return isSameTemplateArgument(Arg1, Arg2);
8099 });
8100 }
8101
8102 llvm_unreachable("Unhandled template argument kind");
8103}
8104
8106 // Handle the non-qualified case efficiently.
8107 if (!T.hasLocalQualifiers()) {
8108 // Handle the common positive case fast.
8109 if (const auto *AT = dyn_cast<ArrayType>(T))
8110 return AT;
8111 }
8112
8113 // Handle the common negative case fast.
8114 if (!isa<ArrayType>(T.getCanonicalType()))
8115 return nullptr;
8116
8117 // Apply any qualifiers from the array type to the element type. This
8118 // implements C99 6.7.3p8: "If the specification of an array type includes
8119 // any type qualifiers, the element type is so qualified, not the array type."
8120
8121 // If we get here, we either have type qualifiers on the type, or we have
8122 // sugar such as a typedef in the way. If we have type qualifiers on the type
8123 // we must propagate them down into the element type.
8124
8125 SplitQualType split = T.getSplitDesugaredType();
8126 Qualifiers qs = split.Quals;
8127
8128 // If we have a simple case, just return now.
8129 const auto *ATy = dyn_cast<ArrayType>(split.Ty);
8130 if (!ATy || qs.empty())
8131 return ATy;
8132
8133 // Otherwise, we have an array and we have qualifiers on it. Push the
8134 // qualifiers into the array element type and return a new array type.
8135 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
8136
8137 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
8138 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
8139 CAT->getSizeExpr(),
8140 CAT->getSizeModifier(),
8141 CAT->getIndexTypeCVRQualifiers()));
8142 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
8144 IAT->getSizeModifier(),
8145 IAT->getIndexTypeCVRQualifiers()));
8146
8147 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
8149 NewEltTy, DSAT->getSizeExpr(), DSAT->getSizeModifier(),
8150 DSAT->getIndexTypeCVRQualifiers()));
8151
8152 const auto *VAT = cast<VariableArrayType>(ATy);
8153 return cast<ArrayType>(
8154 getVariableArrayType(NewEltTy, VAT->getSizeExpr(), VAT->getSizeModifier(),
8155 VAT->getIndexTypeCVRQualifiers()));
8156}
8157
8159 if (getLangOpts().HLSL && T.getAddressSpace() == LangAS::hlsl_groupshared)
8160 return getLValueReferenceType(T);
8161 if (getLangOpts().HLSL && T->isConstantArrayType())
8162 return getArrayParameterType(T);
8163 if (T->isArrayType() || T->isFunctionType())
8164 return getDecayedType(T);
8165 return T;
8166}
8167
8171 return T.getUnqualifiedType();
8172}
8173
8175 // C++ [except.throw]p3:
8176 // A throw-expression initializes a temporary object, called the exception
8177 // object, the type of which is determined by removing any top-level
8178 // cv-qualifiers from the static type of the operand of throw and adjusting
8179 // the type from "array of T" or "function returning T" to "pointer to T"
8180 // or "pointer to function returning T", [...]
8182 if (T->isArrayType() || T->isFunctionType())
8183 T = getDecayedType(T);
8184 return T.getUnqualifiedType();
8185}
8186
8187/// getArrayDecayedType - Return the properly qualified result of decaying the
8188/// specified array type to a pointer. This operation is non-trivial when
8189/// handling typedefs etc. The canonical type of "T" must be an array type,
8190/// this returns a pointer to a properly qualified element of the array.
8191///
8192/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
8194 // Get the element type with 'getAsArrayType' so that we don't lose any
8195 // typedefs in the element type of the array. This also handles propagation
8196 // of type qualifiers from the array type into the element type if present
8197 // (C99 6.7.3p8).
8198 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
8199 assert(PrettyArrayType && "Not an array type!");
8200
8201 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
8202
8203 // int x[restrict 4] -> int *restrict
8205 PrettyArrayType->getIndexTypeQualifiers());
8206
8207 // int x[_Nullable] -> int * _Nullable
8208 if (auto Nullability = Ty->getNullability()) {
8209 Result = getAttributedType(*Nullability, Result, Result);
8210 }
8211 return Result;
8212}
8213
8215 return getBaseElementType(array->getElementType());
8216}
8217
8219 Qualifiers qs;
8220 while (true) {
8221 SplitQualType split = type.getSplitDesugaredType();
8222 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
8223 if (!array) break;
8224
8225 type = array->getElementType();
8227 }
8228
8229 return getQualifiedType(type, qs);
8230}
8231
8233 uint64_t ElementCount = 1;
8234 do {
8235 ElementCount *= CA->getZExtSize();
8236 CA = dyn_cast_if_present<ConstantArrayType>(
8238 } while (CA);
8239 return ElementCount;
8240}
8241
8242uint64_t
8244 if (!AILE)
8245 return 0;
8246
8247 uint64_t ElementCount = 1;
8248
8249 do {
8250 ElementCount *= AILE->getArraySize().getZExtValue();
8251 AILE = dyn_cast<ArrayInitLoopExpr>(AILE->getSubExpr());
8252 } while (AILE);
8253
8254 return ElementCount;
8255}
8256
8257/// getFloatingRank - Return a relative rank for floating point types.
8258/// This routine will assert if passed a built-in type that isn't a float.
8260 if (const auto *CT = T->getAs<ComplexType>())
8261 return getFloatingRank(CT->getElementType());
8262
8263 switch (T->castAs<BuiltinType>()->getKind()) {
8264 default: llvm_unreachable("getFloatingRank(): not a floating type");
8265 case BuiltinType::Float16: return Float16Rank;
8266 case BuiltinType::Half: return HalfRank;
8267 case BuiltinType::Float: return FloatRank;
8268 case BuiltinType::Double: return DoubleRank;
8269 case BuiltinType::LongDouble: return LongDoubleRank;
8270 case BuiltinType::Float128: return Float128Rank;
8271 case BuiltinType::BFloat16: return BFloat16Rank;
8272 case BuiltinType::Ibm128: return Ibm128Rank;
8273 }
8274}
8275
8276/// getFloatingTypeOrder - Compare the rank of the two specified floating
8277/// point types, ignoring the domain of the type (i.e. 'double' ==
8278/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
8279/// LHS < RHS, return -1.
8281 FloatingRank LHSR = getFloatingRank(LHS);
8282 FloatingRank RHSR = getFloatingRank(RHS);
8283
8284 if (LHSR == RHSR)
8285 return 0;
8286 if (LHSR > RHSR)
8287 return 1;
8288 return -1;
8289}
8290
8293 return 0;
8294 return getFloatingTypeOrder(LHS, RHS);
8295}
8296
8297/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
8298/// routine will assert if passed a built-in type that isn't an integer or enum,
8299/// or if it is not canonicalized.
8300unsigned ASTContext::getIntegerRank(const Type *T) const {
8301 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
8302
8303 // Results in this 'losing' to any type of the same size, but winning if
8304 // larger.
8305 if (const auto *EIT = dyn_cast<BitIntType>(T))
8306 return 0 + (EIT->getNumBits() << 3);
8307
8308 if (const auto *OBT = dyn_cast<OverflowBehaviorType>(T))
8309 return getIntegerRank(OBT->getUnderlyingType().getTypePtr());
8310
8311 switch (cast<BuiltinType>(T)->getKind()) {
8312 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
8313 case BuiltinType::Bool:
8314 return 1 + (getIntWidth(BoolTy) << 3);
8315 case BuiltinType::Char_S:
8316 case BuiltinType::Char_U:
8317 case BuiltinType::SChar:
8318 case BuiltinType::UChar:
8319 return 2 + (getIntWidth(CharTy) << 3);
8320 case BuiltinType::Short:
8321 case BuiltinType::UShort:
8322 return 3 + (getIntWidth(ShortTy) << 3);
8323 case BuiltinType::Int:
8324 case BuiltinType::UInt:
8325 return 4 + (getIntWidth(IntTy) << 3);
8326 case BuiltinType::Long:
8327 case BuiltinType::ULong:
8328 return 5 + (getIntWidth(LongTy) << 3);
8329 case BuiltinType::LongLong:
8330 case BuiltinType::ULongLong:
8331 return 6 + (getIntWidth(LongLongTy) << 3);
8332 case BuiltinType::Int128:
8333 case BuiltinType::UInt128:
8334 return 7 + (getIntWidth(Int128Ty) << 3);
8335
8336 // "The ranks of char8_t, char16_t, char32_t, and wchar_t equal the ranks of
8337 // their underlying types" [c++20 conv.rank]
8338 case BuiltinType::Char8:
8339 return getIntegerRank(UnsignedCharTy.getTypePtr());
8340 case BuiltinType::Char16:
8341 return getIntegerRank(
8342 getFromTargetType(Target->getChar16Type()).getTypePtr());
8343 case BuiltinType::Char32:
8344 return getIntegerRank(
8345 getFromTargetType(Target->getChar32Type()).getTypePtr());
8346 case BuiltinType::WChar_S:
8347 case BuiltinType::WChar_U:
8348 return getIntegerRank(
8349 getFromTargetType(Target->getWCharType()).getTypePtr());
8350 }
8351}
8352
8353/// Whether this is a promotable bitfield reference according
8354/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
8355///
8356/// \returns the type this bit-field will promote to, or NULL if no
8357/// promotion occurs.
8359 if (E->isTypeDependent() || E->isValueDependent())
8360 return {};
8361
8362 // C++ [conv.prom]p5:
8363 // If the bit-field has an enumerated type, it is treated as any other
8364 // value of that type for promotion purposes.
8366 return {};
8367
8368 // FIXME: We should not do this unless E->refersToBitField() is true. This
8369 // matters in C where getSourceBitField() will find bit-fields for various
8370 // cases where the source expression is not a bit-field designator.
8371
8372 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
8373 if (!Field)
8374 return {};
8375
8376 QualType FT = Field->getType();
8377
8378 uint64_t BitWidth = Field->getBitWidthValue();
8379 uint64_t IntSize = getTypeSize(IntTy);
8380 // C++ [conv.prom]p5:
8381 // A prvalue for an integral bit-field can be converted to a prvalue of type
8382 // int if int can represent all the values of the bit-field; otherwise, it
8383 // can be converted to unsigned int if unsigned int can represent all the
8384 // values of the bit-field. If the bit-field is larger yet, no integral
8385 // promotion applies to it.
8386 // C11 6.3.1.1/2:
8387 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
8388 // If an int can represent all values of the original type (as restricted by
8389 // the width, for a bit-field), the value is converted to an int; otherwise,
8390 // it is converted to an unsigned int.
8391 //
8392 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
8393 // We perform that promotion here to match GCC and C++.
8394 // FIXME: C does not permit promotion of an enum bit-field whose rank is
8395 // greater than that of 'int'. We perform that promotion to match GCC.
8396 //
8397 // C23 6.3.1.1p2:
8398 // The value from a bit-field of a bit-precise integer type is converted to
8399 // the corresponding bit-precise integer type. (The rest is the same as in
8400 // C11.)
8401 if (QualType QT = Field->getType(); QT->isBitIntType())
8402 return QT;
8403
8404 if (BitWidth < IntSize)
8405 return IntTy;
8406
8407 if (BitWidth == IntSize)
8408 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
8409
8410 // Bit-fields wider than int are not subject to promotions, and therefore act
8411 // like the base type. GCC has some weird bugs in this area that we
8412 // deliberately do not follow (GCC follows a pre-standard resolution to
8413 // C's DR315 which treats bit-width as being part of the type, and this leaks
8414 // into their semantics in some cases).
8415 return {};
8416}
8417
8418/// getPromotedIntegerType - Returns the type that Promotable will
8419/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
8420/// integer type.
8422 assert(!Promotable.isNull());
8423 assert(isPromotableIntegerType(Promotable));
8424 if (const auto *ED = Promotable->getAsEnumDecl())
8425 return ED->getPromotionType();
8426
8427 // OverflowBehaviorTypes promote their underlying type and preserve OBT
8428 // qualifier.
8429 if (const auto *OBT = Promotable->getAs<OverflowBehaviorType>()) {
8430 QualType PromotedUnderlying =
8431 getPromotedIntegerType(OBT->getUnderlyingType());
8432 return getOverflowBehaviorType(OBT->getBehaviorKind(), PromotedUnderlying);
8433 }
8434
8435 if (const auto *BT = Promotable->getAs<BuiltinType>()) {
8436 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
8437 // (3.9.1) can be converted to a prvalue of the first of the following
8438 // types that can represent all the values of its underlying type:
8439 // int, unsigned int, long int, unsigned long int, long long int, or
8440 // unsigned long long int [...]
8441 // FIXME: Is there some better way to compute this?
8442 if (BT->getKind() == BuiltinType::WChar_S ||
8443 BT->getKind() == BuiltinType::WChar_U ||
8444 BT->getKind() == BuiltinType::Char8 ||
8445 BT->getKind() == BuiltinType::Char16 ||
8446 BT->getKind() == BuiltinType::Char32) {
8447 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
8448 uint64_t FromSize = getTypeSize(BT);
8449 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
8451 for (const auto &PT : PromoteTypes) {
8452 uint64_t ToSize = getTypeSize(PT);
8453 if (FromSize < ToSize ||
8454 (FromSize == ToSize && FromIsSigned == PT->isSignedIntegerType()))
8455 return PT;
8456 }
8457 llvm_unreachable("char type should fit into long long");
8458 }
8459 }
8460
8461 // At this point, we should have a signed or unsigned integer type.
8462 if (Promotable->isSignedIntegerType())
8463 return IntTy;
8464 uint64_t PromotableSize = getIntWidth(Promotable);
8465 uint64_t IntSize = getIntWidth(IntTy);
8466 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
8467 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
8468}
8469
8470/// Recurses in pointer/array types until it finds an objc retainable
8471/// type and returns its ownership.
8473 while (!T.isNull()) {
8474 if (T.getObjCLifetime() != Qualifiers::OCL_None)
8475 return T.getObjCLifetime();
8476 if (T->isArrayType())
8478 else if (const auto *PT = T->getAs<PointerType>())
8479 T = PT->getPointeeType();
8480 else if (const auto *RT = T->getAs<ReferenceType>())
8481 T = RT->getPointeeType();
8482 else
8483 break;
8484 }
8485
8486 return Qualifiers::OCL_None;
8487}
8488
8489static const Type *getIntegerTypeForEnum(const EnumType *ET) {
8490 // Incomplete enum types are not treated as integer types.
8491 // FIXME: In C++, enum types are never integer types.
8492 const EnumDecl *ED = ET->getDecl()->getDefinitionOrSelf();
8493 if (ED->isComplete() && !ED->isScoped())
8494 return ED->getIntegerType().getTypePtr();
8495 return nullptr;
8496}
8497
8498/// getIntegerTypeOrder - Returns the highest ranked integer type:
8499/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
8500/// LHS < RHS, return -1.
8502 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
8503 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
8504
8505 // Unwrap enums to their underlying type.
8506 if (const auto *ET = dyn_cast<EnumType>(LHSC))
8507 LHSC = getIntegerTypeForEnum(ET);
8508 if (const auto *ET = dyn_cast<EnumType>(RHSC))
8509 RHSC = getIntegerTypeForEnum(ET);
8510
8511 if (LHSC == RHSC) return 0;
8512
8513 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
8514 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
8515
8516 unsigned LHSRank = getIntegerRank(LHSC);
8517 unsigned RHSRank = getIntegerRank(RHSC);
8518
8519 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
8520 if (LHSRank == RHSRank) return 0;
8521 return LHSRank > RHSRank ? 1 : -1;
8522 }
8523
8524 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
8525 if (LHSUnsigned) {
8526 // If the unsigned [LHS] type is larger, return it.
8527 if (LHSRank >= RHSRank)
8528 return 1;
8529
8530 // If the signed type can represent all values of the unsigned type, it
8531 // wins. Because we are dealing with 2's complement and types that are
8532 // powers of two larger than each other, this is always safe.
8533 return -1;
8534 }
8535
8536 // If the unsigned [RHS] type is larger, return it.
8537 if (RHSRank >= LHSRank)
8538 return -1;
8539
8540 // If the signed type can represent all values of the unsigned type, it
8541 // wins. Because we are dealing with 2's complement and types that are
8542 // powers of two larger than each other, this is always safe.
8543 return 1;
8544}
8545
8547 if (CFConstantStringTypeDecl)
8548 return CFConstantStringTypeDecl;
8549
8550 assert(!CFConstantStringTagDecl &&
8551 "tag and typedef should be initialized together");
8552 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
8553 CFConstantStringTagDecl->startDefinition();
8554
8555 struct {
8556 QualType Type;
8557 const char *Name;
8558 } Fields[5];
8559 unsigned Count = 0;
8560
8561 /// Objective-C ABI
8562 ///
8563 /// typedef struct __NSConstantString_tag {
8564 /// const int *isa;
8565 /// int flags;
8566 /// const char *str;
8567 /// long length;
8568 /// } __NSConstantString;
8569 ///
8570 /// Swift ABI (4.1, 4.2)
8571 ///
8572 /// typedef struct __NSConstantString_tag {
8573 /// uintptr_t _cfisa;
8574 /// uintptr_t _swift_rc;
8575 /// _Atomic(uint64_t) _cfinfoa;
8576 /// const char *_ptr;
8577 /// uint32_t _length;
8578 /// } __NSConstantString;
8579 ///
8580 /// Swift ABI (5.0)
8581 ///
8582 /// typedef struct __NSConstantString_tag {
8583 /// uintptr_t _cfisa;
8584 /// uintptr_t _swift_rc;
8585 /// _Atomic(uint64_t) _cfinfoa;
8586 /// const char *_ptr;
8587 /// uintptr_t _length;
8588 /// } __NSConstantString;
8589
8590 const auto CFRuntime = getLangOpts().CFRuntime;
8591 if (static_cast<unsigned>(CFRuntime) <
8592 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
8593 Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
8594 Fields[Count++] = { IntTy, "flags" };
8595 Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
8596 Fields[Count++] = { LongTy, "length" };
8597 } else {
8598 Fields[Count++] = { getUIntPtrType(), "_cfisa" };
8599 Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
8600 Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
8601 Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
8604 Fields[Count++] = { IntTy, "_ptr" };
8605 else
8606 Fields[Count++] = { getUIntPtrType(), "_ptr" };
8607 }
8608
8609 // Create fields
8610 for (unsigned i = 0; i < Count; ++i) {
8611 FieldDecl *Field =
8612 FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
8613 SourceLocation(), &Idents.get(Fields[i].Name),
8614 Fields[i].Type, /*TInfo=*/nullptr,
8615 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
8616 Field->setAccess(AS_public);
8617 CFConstantStringTagDecl->addDecl(Field);
8618 }
8619
8620 CFConstantStringTagDecl->completeDefinition();
8621 // This type is designed to be compatible with NSConstantString, but cannot
8622 // use the same name, since NSConstantString is an interface.
8623 CanQualType tagType = getCanonicalTagType(CFConstantStringTagDecl);
8624 CFConstantStringTypeDecl =
8625 buildImplicitTypedef(tagType, "__NSConstantString");
8626
8627 return CFConstantStringTypeDecl;
8628}
8629
8631 if (!CFConstantStringTagDecl)
8632 getCFConstantStringDecl(); // Build the tag and the typedef.
8633 return CFConstantStringTagDecl;
8634}
8635
8636// getCFConstantStringType - Return the type used for constant CFStrings.
8641
8643 if (ObjCSuperType.isNull()) {
8644 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
8645 getTranslationUnitDecl()->addDecl(ObjCSuperTypeDecl);
8646 ObjCSuperType = getCanonicalTagType(ObjCSuperTypeDecl);
8647 }
8648 return ObjCSuperType;
8649}
8650
8652 const auto *TT = T->castAs<TypedefType>();
8653 CFConstantStringTypeDecl = cast<TypedefDecl>(TT->getDecl());
8654 CFConstantStringTagDecl = TT->castAsRecordDecl();
8655}
8656
8658 if (BlockDescriptorType)
8659 return getCanonicalTagType(BlockDescriptorType);
8660
8661 RecordDecl *RD;
8662 // FIXME: Needs the FlagAppleBlock bit.
8663 RD = buildImplicitRecord("__block_descriptor");
8664 RD->startDefinition();
8665
8666 QualType FieldTypes[] = {
8669 };
8670
8671 static const char *const FieldNames[] = {
8672 "reserved",
8673 "Size"
8674 };
8675
8676 for (size_t i = 0; i < 2; ++i) {
8678 *this, RD, SourceLocation(), SourceLocation(),
8679 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
8680 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
8681 Field->setAccess(AS_public);
8682 RD->addDecl(Field);
8683 }
8684
8685 RD->completeDefinition();
8686
8687 BlockDescriptorType = RD;
8688
8689 return getCanonicalTagType(BlockDescriptorType);
8690}
8691
8693 if (BlockDescriptorExtendedType)
8694 return getCanonicalTagType(BlockDescriptorExtendedType);
8695
8696 RecordDecl *RD;
8697 // FIXME: Needs the FlagAppleBlock bit.
8698 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
8699 RD->startDefinition();
8700
8701 QualType FieldTypes[] = {
8706 };
8707
8708 static const char *const FieldNames[] = {
8709 "reserved",
8710 "Size",
8711 "CopyFuncPtr",
8712 "DestroyFuncPtr"
8713 };
8714
8715 for (size_t i = 0; i < 4; ++i) {
8717 *this, RD, SourceLocation(), SourceLocation(),
8718 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
8719 /*BitWidth=*/nullptr,
8720 /*Mutable=*/false, ICIS_NoInit);
8721 Field->setAccess(AS_public);
8722 RD->addDecl(Field);
8723 }
8724
8725 RD->completeDefinition();
8726
8727 BlockDescriptorExtendedType = RD;
8728 return getCanonicalTagType(BlockDescriptorExtendedType);
8729}
8730
8732 const auto *BT = dyn_cast<BuiltinType>(T);
8733
8734 if (!BT) {
8735 if (isa<PipeType>(T))
8736 return OCLTK_Pipe;
8737
8738 return OCLTK_Default;
8739 }
8740
8741 switch (BT->getKind()) {
8742#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8743 case BuiltinType::Id: \
8744 return OCLTK_Image;
8745#include "clang/Basic/OpenCLImageTypes.def"
8746
8747 case BuiltinType::OCLClkEvent:
8748 return OCLTK_ClkEvent;
8749
8750 case BuiltinType::OCLEvent:
8751 return OCLTK_Event;
8752
8753 case BuiltinType::OCLQueue:
8754 return OCLTK_Queue;
8755
8756 case BuiltinType::OCLReserveID:
8757 return OCLTK_ReserveID;
8758
8759 case BuiltinType::OCLSampler:
8760 return OCLTK_Sampler;
8761
8762 default:
8763 return OCLTK_Default;
8764 }
8765}
8766
8768 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
8769}
8770
8771/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
8772/// requires copy/dispose. Note that this must match the logic
8773/// in buildByrefHelpers.
8775 const VarDecl *D) {
8776 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
8777 const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
8778 if (!copyExpr && record->hasTrivialDestructor()) return false;
8779
8780 return true;
8781 }
8782
8784 return true;
8785
8786 // The block needs copy/destroy helpers if Ty is non-trivial to destructively
8787 // move or destroy.
8789 return true;
8790
8791 if (!Ty->isObjCRetainableType()) return false;
8792
8793 Qualifiers qs = Ty.getQualifiers();
8794
8795 // If we have lifetime, that dominates.
8796 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
8797 switch (lifetime) {
8798 case Qualifiers::OCL_None: llvm_unreachable("impossible");
8799
8800 // These are just bits as far as the runtime is concerned.
8803 return false;
8804
8805 // These cases should have been taken care of when checking the type's
8806 // non-triviality.
8809 llvm_unreachable("impossible");
8810 }
8811 llvm_unreachable("fell out of lifetime switch!");
8812 }
8813 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
8815}
8816
8818 Qualifiers::ObjCLifetime &LifeTime,
8819 bool &HasByrefExtendedLayout) const {
8820 if (!getLangOpts().ObjC ||
8821 getLangOpts().getGC() != LangOptions::NonGC)
8822 return false;
8823
8824 HasByrefExtendedLayout = false;
8825 if (Ty->isRecordType()) {
8826 HasByrefExtendedLayout = true;
8827 LifeTime = Qualifiers::OCL_None;
8828 } else if ((LifeTime = Ty.getObjCLifetime())) {
8829 // Honor the ARC qualifiers.
8830 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
8831 // The MRR rule.
8833 } else {
8834 LifeTime = Qualifiers::OCL_None;
8835 }
8836 return true;
8837}
8838
8840 assert(Target && "Expected target to be initialized");
8841 const llvm::Triple &T = Target->getTriple();
8842 // Windows is LLP64 rather than LP64
8843 if (T.isOSWindows() && T.isArch64Bit())
8844 return UnsignedLongLongTy;
8845 return UnsignedLongTy;
8846}
8847
8849 assert(Target && "Expected target to be initialized");
8850 const llvm::Triple &T = Target->getTriple();
8851 // Windows is LLP64 rather than LP64
8852 if (T.isOSWindows() && T.isArch64Bit())
8853 return LongLongTy;
8854 return LongTy;
8855}
8856
8858 if (!ObjCInstanceTypeDecl)
8859 ObjCInstanceTypeDecl =
8860 buildImplicitTypedef(getObjCIdType(), "instancetype");
8861 return ObjCInstanceTypeDecl;
8862}
8863
8864// This returns true if a type has been typedefed to BOOL:
8865// typedef <type> BOOL;
8867 if (const auto *TT = dyn_cast<TypedefType>(T))
8868 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
8869 return II->isStr("BOOL");
8870
8871 return false;
8872}
8873
8874/// getObjCEncodingTypeSize returns size of type for objective-c encoding
8875/// purpose.
8877 if (!type->isIncompleteArrayType() && type->isIncompleteType())
8878 return CharUnits::Zero();
8879
8881
8882 // Make all integer and enum types at least as large as an int
8883 if (sz.isPositive() && type->isIntegralOrEnumerationType())
8884 sz = std::max(sz, getTypeSizeInChars(IntTy));
8885 // Treat arrays as pointers, since that's how they're passed in.
8886 else if (type->isArrayType())
8888 return sz;
8889}
8890
8897
8900 if (!VD->isInline())
8902
8903 // In almost all cases, it's a weak definition.
8904 auto *First = VD->getFirstDecl();
8905 if (First->isInlineSpecified() || !First->isStaticDataMember())
8907
8908 // If there's a file-context declaration in this translation unit, it's a
8909 // non-discardable definition.
8910 for (auto *D : VD->redecls())
8912 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
8914
8915 // If we've not seen one yet, we don't know.
8917}
8918
8919static std::string charUnitsToString(CharUnits CU) {
8920 return llvm::itostr(CU.getQuantity());
8921}
8922
8923/// getObjCEncodingForBlock - Return the encoded type for this block
8924/// declaration.
8926 std::string S;
8927
8928 const BlockDecl *Decl = Expr->getBlockDecl();
8929 QualType BlockTy =
8931 QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType();
8932 // Encode result type.
8933 if (getLangOpts().EncodeExtendedBlockSig)
8935 true /*Extended*/);
8936 else
8937 getObjCEncodingForType(BlockReturnTy, S);
8938 // Compute size of all parameters.
8939 // Start with computing size of a pointer in number of bytes.
8940 // FIXME: There might(should) be a better way of doing this computation!
8942 CharUnits ParmOffset = PtrSize;
8943 for (auto *PI : Decl->parameters()) {
8944 QualType PType = PI->getType();
8946 if (sz.isZero())
8947 continue;
8948 assert(sz.isPositive() && "BlockExpr - Incomplete param type");
8949 ParmOffset += sz;
8950 }
8951 // Size of the argument frame
8952 S += charUnitsToString(ParmOffset);
8953 // Block pointer and offset.
8954 S += "@?0";
8955
8956 // Argument types.
8957 ParmOffset = PtrSize;
8958 for (auto *PVDecl : Decl->parameters()) {
8959 QualType PType = PVDecl->getOriginalType();
8960 if (const auto *AT =
8961 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8962 // Use array's original type only if it has known number of
8963 // elements.
8964 if (!isa<ConstantArrayType>(AT))
8965 PType = PVDecl->getType();
8966 } else if (PType->isFunctionType())
8967 PType = PVDecl->getType();
8968 if (getLangOpts().EncodeExtendedBlockSig)
8970 S, true /*Extended*/);
8971 else
8972 getObjCEncodingForType(PType, S);
8973 S += charUnitsToString(ParmOffset);
8974 ParmOffset += getObjCEncodingTypeSize(PType);
8975 }
8976
8977 return S;
8978}
8979
8980std::string
8982 std::string S;
8983 // Encode result type.
8984 getObjCEncodingForType(Decl->getReturnType(), S);
8985 CharUnits ParmOffset;
8986 // Compute size of all parameters.
8987 for (auto *PI : Decl->parameters()) {
8988 QualType PType = PI->getType();
8990 if (sz.isZero())
8991 continue;
8992
8993 assert(sz.isPositive() &&
8994 "getObjCEncodingForFunctionDecl - Incomplete param type");
8995 ParmOffset += sz;
8996 }
8997 S += charUnitsToString(ParmOffset);
8998 ParmOffset = CharUnits::Zero();
8999
9000 // Argument types.
9001 for (auto *PVDecl : Decl->parameters()) {
9002 QualType PType = PVDecl->getOriginalType();
9003 if (const auto *AT =
9004 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
9005 // Use array's original type only if it has known number of
9006 // elements.
9007 if (!isa<ConstantArrayType>(AT))
9008 PType = PVDecl->getType();
9009 } else if (PType->isFunctionType())
9010 PType = PVDecl->getType();
9011 getObjCEncodingForType(PType, S);
9012 S += charUnitsToString(ParmOffset);
9013 ParmOffset += getObjCEncodingTypeSize(PType);
9014 }
9015
9016 return S;
9017}
9018
9019/// getObjCEncodingForMethodParameter - Return the encoded type for a single
9020/// method parameter or return type. If Extended, include class names and
9021/// block object types.
9023 QualType T, std::string& S,
9024 bool Extended) const {
9025 // Encode type qualifier, 'in', 'inout', etc. for the parameter.
9027 // Encode parameter type.
9028 ObjCEncOptions Options = ObjCEncOptions()
9029 .setExpandPointedToStructures()
9030 .setExpandStructures()
9031 .setIsOutermostType();
9032 if (Extended)
9033 Options.setEncodeBlockParameters().setEncodeClassNames();
9034 getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr);
9035}
9036
9037/// getObjCEncodingForMethodDecl - Return the encoded type for this method
9038/// declaration.
9040 bool Extended) const {
9041 // FIXME: This is not very efficient.
9042 // Encode return type.
9043 std::string S;
9044 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
9045 Decl->getReturnType(), S, Extended);
9046 // Compute size of all parameters.
9047 // Start with computing size of a pointer in number of bytes.
9048 // FIXME: There might(should) be a better way of doing this computation!
9050 // The first two arguments (self and _cmd) are pointers; account for
9051 // their size.
9052 CharUnits ParmOffset = 2 * PtrSize;
9053 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
9054 E = Decl->sel_param_end(); PI != E; ++PI) {
9055 QualType PType = (*PI)->getType();
9057 if (sz.isZero())
9058 continue;
9059
9060 assert(sz.isPositive() &&
9061 "getObjCEncodingForMethodDecl - Incomplete param type");
9062 ParmOffset += sz;
9063 }
9064 S += charUnitsToString(ParmOffset);
9065 S += "@0:";
9066 S += charUnitsToString(PtrSize);
9067
9068 // Argument types.
9069 ParmOffset = 2 * PtrSize;
9070 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
9071 E = Decl->sel_param_end(); PI != E; ++PI) {
9072 const ParmVarDecl *PVDecl = *PI;
9073 QualType PType = PVDecl->getOriginalType();
9074 if (const auto *AT =
9075 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
9076 // Use array's original type only if it has known number of
9077 // elements.
9078 if (!isa<ConstantArrayType>(AT))
9079 PType = PVDecl->getType();
9080 } else if (PType->isFunctionType())
9081 PType = PVDecl->getType();
9083 PType, S, Extended);
9084 S += charUnitsToString(ParmOffset);
9085 ParmOffset += getObjCEncodingTypeSize(PType);
9086 }
9087
9088 return S;
9089}
9090
9093 const ObjCPropertyDecl *PD,
9094 const Decl *Container) const {
9095 if (!Container)
9096 return nullptr;
9097 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
9098 for (auto *PID : CID->property_impls())
9099 if (PID->getPropertyDecl() == PD)
9100 return PID;
9101 } else {
9102 const auto *OID = cast<ObjCImplementationDecl>(Container);
9103 for (auto *PID : OID->property_impls())
9104 if (PID->getPropertyDecl() == PD)
9105 return PID;
9106 }
9107 return nullptr;
9108}
9109
9110/// getObjCEncodingForPropertyDecl - Return the encoded type for this
9111/// property declaration. If non-NULL, Container must be either an
9112/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
9113/// NULL when getting encodings for protocol properties.
9114/// Property attributes are stored as a comma-delimited C string. The simple
9115/// attributes readonly and bycopy are encoded as single characters. The
9116/// parametrized attributes, getter=name, setter=name, and ivar=name, are
9117/// encoded as single characters, followed by an identifier. Property types
9118/// are also encoded as a parametrized attribute. The characters used to encode
9119/// these attributes are defined by the following enumeration:
9120/// @code
9121/// enum PropertyAttributes {
9122/// kPropertyReadOnly = 'R', // property is read-only.
9123/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
9124/// kPropertyByref = '&', // property is a reference to the value last assigned
9125/// kPropertyDynamic = 'D', // property is dynamic
9126/// kPropertyGetter = 'G', // followed by getter selector name
9127/// kPropertySetter = 'S', // followed by setter selector name
9128/// kPropertyInstanceVariable = 'V' // followed by instance variable name
9129/// kPropertyType = 'T' // followed by old-style type encoding.
9130/// kPropertyWeak = 'W' // 'weak' property
9131/// kPropertyStrong = 'P' // property GC'able
9132/// kPropertyNonAtomic = 'N' // property non-atomic
9133/// kPropertyOptional = '?' // property optional
9134/// };
9135/// @endcode
9136std::string
9138 const Decl *Container) const {
9139 // Collect information from the property implementation decl(s).
9140 bool Dynamic = false;
9141 ObjCPropertyImplDecl *SynthesizePID = nullptr;
9142
9143 if (ObjCPropertyImplDecl *PropertyImpDecl =
9145 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
9146 Dynamic = true;
9147 else
9148 SynthesizePID = PropertyImpDecl;
9149 }
9150
9151 // FIXME: This is not very efficient.
9152 std::string S = "T";
9153
9154 // Encode result type.
9155 // GCC has some special rules regarding encoding of properties which
9156 // closely resembles encoding of ivars.
9158
9159 if (PD->isOptional())
9160 S += ",?";
9161
9162 if (PD->isReadOnly()) {
9163 S += ",R";
9165 S += ",C";
9167 S += ",&";
9169 S += ",W";
9170 } else {
9171 switch (PD->getSetterKind()) {
9172 case ObjCPropertyDecl::Assign: break;
9173 case ObjCPropertyDecl::Copy: S += ",C"; break;
9174 case ObjCPropertyDecl::Retain: S += ",&"; break;
9175 case ObjCPropertyDecl::Weak: S += ",W"; break;
9176 }
9177 }
9178
9179 // It really isn't clear at all what this means, since properties
9180 // are "dynamic by default".
9181 if (Dynamic)
9182 S += ",D";
9183
9185 S += ",N";
9186
9188 S += ",G";
9189 S += PD->getGetterName().getAsString();
9190 }
9191
9193 S += ",S";
9194 S += PD->getSetterName().getAsString();
9195 }
9196
9197 if (SynthesizePID) {
9198 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
9199 S += ",V";
9200 S += OID->getNameAsString();
9201 }
9202
9203 // FIXME: OBJCGC: weak & strong
9204 return S;
9205}
9206
9207/// getLegacyIntegralTypeEncoding -
9208/// Another legacy compatibility encoding: 32-bit longs are encoded as
9209/// 'l' or 'L' , but not always. For typedefs, we need to use
9210/// 'i' or 'I' instead if encoding a struct field, or a pointer!
9212 if (PointeeTy->getAs<TypedefType>()) {
9213 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
9214 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
9215 PointeeTy = UnsignedIntTy;
9216 else
9217 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
9218 PointeeTy = IntTy;
9219 }
9220 }
9221}
9222
9224 const FieldDecl *Field,
9225 QualType *NotEncodedT) const {
9226 // We follow the behavior of gcc, expanding structures which are
9227 // directly pointed to, and expanding embedded structures. Note that
9228 // these rules are sufficient to prevent recursive encoding of the
9229 // same type.
9230 getObjCEncodingForTypeImpl(T, S,
9231 ObjCEncOptions()
9232 .setExpandPointedToStructures()
9233 .setExpandStructures()
9234 .setIsOutermostType(),
9235 Field, NotEncodedT);
9236}
9237
9239 std::string& S) const {
9240 // Encode result type.
9241 // GCC has some special rules regarding encoding of properties which
9242 // closely resembles encoding of ivars.
9243 getObjCEncodingForTypeImpl(T, S,
9244 ObjCEncOptions()
9245 .setExpandPointedToStructures()
9246 .setExpandStructures()
9247 .setIsOutermostType()
9248 .setEncodingProperty(),
9249 /*Field=*/nullptr);
9250}
9251
9253 const BuiltinType *BT) {
9255 switch (kind) {
9256 case BuiltinType::Void: return 'v';
9257 case BuiltinType::Bool: return 'B';
9258 case BuiltinType::Char8:
9259 case BuiltinType::Char_U:
9260 case BuiltinType::UChar: return 'C';
9261 case BuiltinType::Char16:
9262 case BuiltinType::UShort: return 'S';
9263 case BuiltinType::Char32:
9264 case BuiltinType::UInt: return 'I';
9265 case BuiltinType::ULong:
9266 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
9267 case BuiltinType::UInt128: return 'T';
9268 case BuiltinType::ULongLong: return 'Q';
9269 case BuiltinType::Char_S:
9270 case BuiltinType::SChar: return 'c';
9271 case BuiltinType::Short: return 's';
9272 case BuiltinType::WChar_S:
9273 case BuiltinType::WChar_U:
9274 case BuiltinType::Int: return 'i';
9275 case BuiltinType::Long:
9276 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
9277 case BuiltinType::LongLong: return 'q';
9278 case BuiltinType::Int128: return 't';
9279 case BuiltinType::Float: return 'f';
9280 case BuiltinType::Double: return 'd';
9281 case BuiltinType::LongDouble: return 'D';
9282 case BuiltinType::NullPtr: return '*'; // like char*
9283
9284 case BuiltinType::BFloat16:
9285 case BuiltinType::Float16:
9286 case BuiltinType::Float128:
9287 case BuiltinType::Ibm128:
9288 case BuiltinType::Half:
9289 case BuiltinType::ShortAccum:
9290 case BuiltinType::Accum:
9291 case BuiltinType::LongAccum:
9292 case BuiltinType::UShortAccum:
9293 case BuiltinType::UAccum:
9294 case BuiltinType::ULongAccum:
9295 case BuiltinType::ShortFract:
9296 case BuiltinType::Fract:
9297 case BuiltinType::LongFract:
9298 case BuiltinType::UShortFract:
9299 case BuiltinType::UFract:
9300 case BuiltinType::ULongFract:
9301 case BuiltinType::SatShortAccum:
9302 case BuiltinType::SatAccum:
9303 case BuiltinType::SatLongAccum:
9304 case BuiltinType::SatUShortAccum:
9305 case BuiltinType::SatUAccum:
9306 case BuiltinType::SatULongAccum:
9307 case BuiltinType::SatShortFract:
9308 case BuiltinType::SatFract:
9309 case BuiltinType::SatLongFract:
9310 case BuiltinType::SatUShortFract:
9311 case BuiltinType::SatUFract:
9312 case BuiltinType::SatULongFract:
9313 // FIXME: potentially need @encodes for these!
9314 return ' ';
9315
9316#define SVE_TYPE(Name, Id, SingletonId) \
9317 case BuiltinType::Id:
9318#include "clang/Basic/AArch64ACLETypes.def"
9319#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9320#include "clang/Basic/RISCVVTypes.def"
9321#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9322#include "clang/Basic/WebAssemblyReferenceTypes.def"
9323#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
9324#include "clang/Basic/AMDGPUTypes.def"
9325#define SPIRV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9326#include "clang/Basic/SPIRVTypes.def"
9327 {
9328 DiagnosticsEngine &Diags = C->getDiagnostics();
9329 Diags.Report(diag::err_unsupported_objc_primitive_encoding)
9330 << QualType(BT, 0);
9331 return ' ';
9332 }
9333
9334 case BuiltinType::ObjCId:
9335 case BuiltinType::ObjCClass:
9336 case BuiltinType::ObjCSel:
9337 llvm_unreachable("@encoding ObjC primitive type");
9338
9339 // OpenCL and placeholder types don't need @encodings.
9340#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
9341 case BuiltinType::Id:
9342#include "clang/Basic/OpenCLImageTypes.def"
9343#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
9344 case BuiltinType::Id:
9345#include "clang/Basic/OpenCLExtensionTypes.def"
9346 case BuiltinType::OCLEvent:
9347 case BuiltinType::OCLClkEvent:
9348 case BuiltinType::OCLQueue:
9349 case BuiltinType::OCLReserveID:
9350 case BuiltinType::OCLSampler:
9351 case BuiltinType::Dependent:
9352#define PPC_VECTOR_TYPE(Name, Id, Size) \
9353 case BuiltinType::Id:
9354#include "clang/Basic/PPCTypes.def"
9355#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9356#include "clang/Basic/HLSLIntangibleTypes.def"
9357#define BUILTIN_TYPE(KIND, ID)
9358#define PLACEHOLDER_TYPE(KIND, ID) \
9359 case BuiltinType::KIND:
9360#include "clang/AST/BuiltinTypes.def"
9361 llvm_unreachable("invalid builtin type for @encode");
9362 }
9363 llvm_unreachable("invalid BuiltinType::Kind value");
9364}
9365
9366static char ObjCEncodingForEnumDecl(const ASTContext *C, const EnumDecl *ED) {
9368
9369 // The encoding of an non-fixed enum type is always 'i', regardless of size.
9370 if (!Enum->isFixed())
9371 return 'i';
9372
9373 // The encoding of a fixed enum type matches its fixed underlying type.
9374 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
9376}
9377
9378static void EncodeBitField(const ASTContext *Ctx, std::string& S,
9379 QualType T, const FieldDecl *FD) {
9380 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
9381 S += 'b';
9382 // The NeXT runtime encodes bit fields as b followed by the number of bits.
9383 // The GNU runtime requires more information; bitfields are encoded as b,
9384 // then the offset (in bits) of the first element, then the type of the
9385 // bitfield, then the size in bits. For example, in this structure:
9386 //
9387 // struct
9388 // {
9389 // int integer;
9390 // int flags:2;
9391 // };
9392 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
9393 // runtime, but b32i2 for the GNU runtime. The reason for this extra
9394 // information is not especially sensible, but we're stuck with it for
9395 // compatibility with GCC, although providing it breaks anything that
9396 // actually uses runtime introspection and wants to work on both runtimes...
9397 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
9398 uint64_t Offset;
9399
9400 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
9401 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), IVD);
9402 } else {
9403 const RecordDecl *RD = FD->getParent();
9404 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
9405 Offset = RL.getFieldOffset(FD->getFieldIndex());
9406 }
9407
9408 S += llvm::utostr(Offset);
9409
9410 if (const auto *ET = T->getAsCanonical<EnumType>())
9411 S += ObjCEncodingForEnumDecl(Ctx, ET->getDecl());
9412 else {
9413 const auto *BT = T->castAs<BuiltinType>();
9414 S += getObjCEncodingForPrimitiveType(Ctx, BT);
9415 }
9416 }
9417 S += llvm::utostr(FD->getBitWidthValue());
9418}
9419
9420// Helper function for determining whether the encoded type string would include
9421// a template specialization type.
9423 bool VisitBasesAndFields) {
9424 T = T->getBaseElementTypeUnsafe();
9425
9426 if (auto *PT = T->getAs<PointerType>())
9428 PT->getPointeeType().getTypePtr(), false);
9429
9430 auto *CXXRD = T->getAsCXXRecordDecl();
9431
9432 if (!CXXRD)
9433 return false;
9434
9436 return true;
9437
9438 if (!CXXRD->hasDefinition() || !VisitBasesAndFields)
9439 return false;
9440
9441 for (const auto &B : CXXRD->bases())
9442 if (hasTemplateSpecializationInEncodedString(B.getType().getTypePtr(),
9443 true))
9444 return true;
9445
9446 for (auto *FD : CXXRD->fields())
9447 if (hasTemplateSpecializationInEncodedString(FD->getType().getTypePtr(),
9448 true))
9449 return true;
9450
9451 return false;
9452}
9453
9454// FIXME: Use SmallString for accumulating string.
9455void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
9456 const ObjCEncOptions Options,
9457 const FieldDecl *FD,
9458 QualType *NotEncodedT) const {
9460 switch (CT->getTypeClass()) {
9461 case Type::Builtin:
9462 case Type::Enum:
9463 if (FD && FD->isBitField())
9464 return EncodeBitField(this, S, T, FD);
9465 if (const auto *BT = dyn_cast<BuiltinType>(CT))
9466 S += getObjCEncodingForPrimitiveType(this, BT);
9467 else
9468 S += ObjCEncodingForEnumDecl(this, cast<EnumType>(CT)->getDecl());
9469 return;
9470
9471 case Type::Complex:
9472 S += 'j';
9473 getObjCEncodingForTypeImpl(T->castAs<ComplexType>()->getElementType(), S,
9474 ObjCEncOptions(),
9475 /*Field=*/nullptr);
9476 return;
9477
9478 case Type::Atomic:
9479 S += 'A';
9480 getObjCEncodingForTypeImpl(T->castAs<AtomicType>()->getValueType(), S,
9481 ObjCEncOptions(),
9482 /*Field=*/nullptr);
9483 return;
9484
9485 // encoding for pointer or reference types.
9486 case Type::Pointer:
9487 case Type::LValueReference:
9488 case Type::RValueReference: {
9489 QualType PointeeTy;
9490 if (isa<PointerType>(CT)) {
9491 const auto *PT = T->castAs<PointerType>();
9492 if (PT->isObjCSelType()) {
9493 S += ':';
9494 return;
9495 }
9496 PointeeTy = PT->getPointeeType();
9497 } else {
9498 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
9499 }
9500
9501 bool isReadOnly = false;
9502 // For historical/compatibility reasons, the read-only qualifier of the
9503 // pointee gets emitted _before_ the '^'. The read-only qualifier of
9504 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
9505 // Also, do not emit the 'r' for anything but the outermost type!
9506 if (T->getAs<TypedefType>()) {
9507 if (Options.IsOutermostType() && T.isConstQualified()) {
9508 isReadOnly = true;
9509 S += 'r';
9510 }
9511 } else if (Options.IsOutermostType()) {
9512 QualType P = PointeeTy;
9513 while (auto PT = P->getAs<PointerType>())
9514 P = PT->getPointeeType();
9515 if (P.isConstQualified()) {
9516 isReadOnly = true;
9517 S += 'r';
9518 }
9519 }
9520 if (isReadOnly) {
9521 // Another legacy compatibility encoding. Some ObjC qualifier and type
9522 // combinations need to be rearranged.
9523 // Rewrite "in const" from "nr" to "rn"
9524 if (StringRef(S).ends_with("nr"))
9525 S.replace(S.end()-2, S.end(), "rn");
9526 }
9527
9528 if (PointeeTy->isCharType()) {
9529 // char pointer types should be encoded as '*' unless it is a
9530 // type that has been typedef'd to 'BOOL'.
9531 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
9532 S += '*';
9533 return;
9534 }
9535 } else if (const auto *RTy = PointeeTy->getAsCanonical<RecordType>()) {
9536 const IdentifierInfo *II = RTy->getDecl()->getIdentifier();
9537 // GCC binary compat: Need to convert "struct objc_class *" to "#".
9538 if (II == &Idents.get("objc_class")) {
9539 S += '#';
9540 return;
9541 }
9542 // GCC binary compat: Need to convert "struct objc_object *" to "@".
9543 if (II == &Idents.get("objc_object")) {
9544 S += '@';
9545 return;
9546 }
9547 // If the encoded string for the class includes template names, just emit
9548 // "^v" for pointers to the class.
9549 if (getLangOpts().CPlusPlus &&
9550 (!getLangOpts().EncodeCXXClassTemplateSpec &&
9552 RTy, Options.ExpandPointedToStructures()))) {
9553 S += "^v";
9554 return;
9555 }
9556 // fall through...
9557 }
9558 S += '^';
9560
9561 ObjCEncOptions NewOptions;
9562 if (Options.ExpandPointedToStructures())
9563 NewOptions.setExpandStructures();
9564 getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions,
9565 /*Field=*/nullptr, NotEncodedT);
9566 return;
9567 }
9568
9569 case Type::ConstantArray:
9570 case Type::IncompleteArray:
9571 case Type::VariableArray: {
9572 const auto *AT = cast<ArrayType>(CT);
9573
9574 if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) {
9575 // Incomplete arrays are encoded as a pointer to the array element.
9576 S += '^';
9577
9578 getObjCEncodingForTypeImpl(
9579 AT->getElementType(), S,
9580 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD);
9581 } else {
9582 S += '[';
9583
9584 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
9585 S += llvm::utostr(CAT->getZExtSize());
9586 else {
9587 //Variable length arrays are encoded as a regular array with 0 elements.
9589 "Unknown array type!");
9590 S += '0';
9591 }
9592
9593 getObjCEncodingForTypeImpl(
9594 AT->getElementType(), S,
9595 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD,
9596 NotEncodedT);
9597 S += ']';
9598 }
9599 return;
9600 }
9601
9602 case Type::FunctionNoProto:
9603 case Type::FunctionProto:
9604 S += '?';
9605 return;
9606
9607 case Type::Record: {
9608 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
9609 S += RDecl->isUnion() ? '(' : '{';
9610 // Anonymous structures print as '?'
9611 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
9612 S += II->getName();
9613 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
9614 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
9615 llvm::raw_string_ostream OS(S);
9616 printTemplateArgumentList(OS, TemplateArgs.asArray(),
9618 }
9619 } else {
9620 S += '?';
9621 }
9622 if (Options.ExpandStructures()) {
9623 S += '=';
9624 if (!RDecl->isUnion()) {
9625 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
9626 } else {
9627 for (const auto *Field : RDecl->fields()) {
9628 if (FD) {
9629 S += '"';
9630 S += Field->getNameAsString();
9631 S += '"';
9632 }
9633
9634 // Special case bit-fields.
9635 if (Field->isBitField()) {
9636 getObjCEncodingForTypeImpl(Field->getType(), S,
9637 ObjCEncOptions().setExpandStructures(),
9638 Field);
9639 } else {
9640 QualType qt = Field->getType();
9642 getObjCEncodingForTypeImpl(
9643 qt, S,
9644 ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
9645 NotEncodedT);
9646 }
9647 }
9648 }
9649 }
9650 S += RDecl->isUnion() ? ')' : '}';
9651 return;
9652 }
9653
9654 case Type::BlockPointer: {
9655 const auto *BT = T->castAs<BlockPointerType>();
9656 S += "@?"; // Unlike a pointer-to-function, which is "^?".
9657 if (Options.EncodeBlockParameters()) {
9658 const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
9659
9660 S += '<';
9661 // Block return type
9662 getObjCEncodingForTypeImpl(FT->getReturnType(), S,
9663 Options.forComponentType(), FD, NotEncodedT);
9664 // Block self
9665 S += "@?";
9666 // Block parameters
9667 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
9668 for (const auto &I : FPT->param_types())
9669 getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD,
9670 NotEncodedT);
9671 }
9672 S += '>';
9673 }
9674 return;
9675 }
9676
9677 case Type::ObjCObject: {
9678 // hack to match legacy encoding of *id and *Class
9679 QualType Ty = getObjCObjectPointerType(CT);
9680 if (Ty->isObjCIdType()) {
9681 S += "{objc_object=}";
9682 return;
9683 }
9684 else if (Ty->isObjCClassType()) {
9685 S += "{objc_class=}";
9686 return;
9687 }
9688 // TODO: Double check to make sure this intentionally falls through.
9689 [[fallthrough]];
9690 }
9691
9692 case Type::ObjCInterface: {
9693 // Ignore protocol qualifiers when mangling at this level.
9694 // @encode(class_name)
9695 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
9696 S += '{';
9697 S += OI->getObjCRuntimeNameAsString();
9698 if (Options.ExpandStructures()) {
9699 S += '=';
9700 SmallVector<const ObjCIvarDecl*, 32> Ivars;
9701 DeepCollectObjCIvars(OI, true, Ivars);
9702 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
9703 const FieldDecl *Field = Ivars[i];
9704 if (Field->isBitField())
9705 getObjCEncodingForTypeImpl(Field->getType(), S,
9706 ObjCEncOptions().setExpandStructures(),
9707 Field);
9708 else
9709 getObjCEncodingForTypeImpl(Field->getType(), S,
9710 ObjCEncOptions().setExpandStructures(), FD,
9711 NotEncodedT);
9712 }
9713 }
9714 S += '}';
9715 return;
9716 }
9717
9718 case Type::ObjCObjectPointer: {
9719 const auto *OPT = T->castAs<ObjCObjectPointerType>();
9720 if (OPT->isObjCIdType()) {
9721 S += '@';
9722 return;
9723 }
9724
9725 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
9726 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
9727 // Since this is a binary compatibility issue, need to consult with
9728 // runtime folks. Fortunately, this is a *very* obscure construct.
9729 S += '#';
9730 return;
9731 }
9732
9733 if (OPT->isObjCQualifiedIdType()) {
9734 getObjCEncodingForTypeImpl(
9735 getObjCIdType(), S,
9736 Options.keepingOnly(ObjCEncOptions()
9737 .setExpandPointedToStructures()
9738 .setExpandStructures()),
9739 FD);
9740 if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
9741 // Note that we do extended encoding of protocol qualifier list
9742 // Only when doing ivar or property encoding.
9743 S += '"';
9744 for (const auto *I : OPT->quals()) {
9745 S += '<';
9746 S += I->getObjCRuntimeNameAsString();
9747 S += '>';
9748 }
9749 S += '"';
9750 }
9751 return;
9752 }
9753
9754 S += '@';
9755 if (OPT->getInterfaceDecl() &&
9756 (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
9757 S += '"';
9758 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
9759 for (const auto *I : OPT->quals()) {
9760 S += '<';
9761 S += I->getObjCRuntimeNameAsString();
9762 S += '>';
9763 }
9764 S += '"';
9765 }
9766 return;
9767 }
9768
9769 // gcc just blithely ignores member pointers.
9770 // FIXME: we should do better than that. 'M' is available.
9771 case Type::MemberPointer:
9772 // This matches gcc's encoding, even though technically it is insufficient.
9773 //FIXME. We should do a better job than gcc.
9774 case Type::Vector:
9775 case Type::ExtVector:
9776 // Until we have a coherent encoding of these three types, issue warning.
9777 if (NotEncodedT)
9778 *NotEncodedT = T;
9779 return;
9780
9781 case Type::ConstantMatrix:
9782 if (NotEncodedT)
9783 *NotEncodedT = T;
9784 return;
9785
9786 case Type::BitInt:
9787 if (NotEncodedT)
9788 *NotEncodedT = T;
9789 return;
9790
9791 // We could see an undeduced auto type here during error recovery.
9792 // Just ignore it.
9793 case Type::Auto:
9794 case Type::DeducedTemplateSpecialization:
9795 return;
9796
9797 case Type::HLSLAttributedResource:
9798 case Type::HLSLInlineSpirv:
9799 case Type::OverflowBehavior:
9800 llvm_unreachable("unexpected type");
9801
9802 case Type::ArrayParameter:
9803 case Type::Pipe:
9804#define ABSTRACT_TYPE(KIND, BASE)
9805#define TYPE(KIND, BASE)
9806#define DEPENDENT_TYPE(KIND, BASE) \
9807 case Type::KIND:
9808#define NON_CANONICAL_TYPE(KIND, BASE) \
9809 case Type::KIND:
9810#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
9811 case Type::KIND:
9812#include "clang/AST/TypeNodes.inc"
9813 llvm_unreachable("@encode for dependent type!");
9814 }
9815 llvm_unreachable("bad type kind!");
9816}
9817
9818void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
9819 std::string &S,
9820 const FieldDecl *FD,
9821 bool includeVBases,
9822 QualType *NotEncodedT) const {
9823 assert(RDecl && "Expected non-null RecordDecl");
9824 assert(!RDecl->isUnion() && "Should not be called for unions");
9825 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
9826 return;
9827
9828 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
9829 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
9830 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
9831
9832 if (CXXRec) {
9833 for (const auto &BI : CXXRec->bases()) {
9834 if (!BI.isVirtual()) {
9835 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9836 if (base->isEmpty())
9837 continue;
9838 uint64_t offs = toBits(layout.getBaseClassOffset(base));
9839 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9840 std::make_pair(offs, base));
9841 }
9842 }
9843 }
9844
9845 for (FieldDecl *Field : RDecl->fields()) {
9846 if (!Field->isZeroLengthBitField() && Field->isZeroSize(*this))
9847 continue;
9848 uint64_t offs = layout.getFieldOffset(Field->getFieldIndex());
9849 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9850 std::make_pair(offs, Field));
9851 }
9852
9853 if (CXXRec && includeVBases) {
9854 for (const auto &BI : CXXRec->vbases()) {
9855 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9856 if (base->isEmpty())
9857 continue;
9858 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
9859 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
9860 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
9861 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
9862 std::make_pair(offs, base));
9863 }
9864 }
9865
9866 CharUnits size;
9867 if (CXXRec) {
9868 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
9869 } else {
9870 size = layout.getSize();
9871 }
9872
9873#ifndef NDEBUG
9874 uint64_t CurOffs = 0;
9875#endif
9876 std::multimap<uint64_t, NamedDecl *>::iterator
9877 CurLayObj = FieldOrBaseOffsets.begin();
9878
9879 if (CXXRec && CXXRec->isDynamicClass() &&
9880 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
9881 if (FD) {
9882 S += "\"_vptr$";
9883 std::string recname = CXXRec->getNameAsString();
9884 if (recname.empty()) recname = "?";
9885 S += recname;
9886 S += '"';
9887 }
9888 S += "^^?";
9889#ifndef NDEBUG
9890 CurOffs += getTypeSize(VoidPtrTy);
9891#endif
9892 }
9893
9894 if (!RDecl->hasFlexibleArrayMember()) {
9895 // Mark the end of the structure.
9896 uint64_t offs = toBits(size);
9897 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9898 std::make_pair(offs, nullptr));
9899 }
9900
9901 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
9902#ifndef NDEBUG
9903 assert(CurOffs <= CurLayObj->first);
9904 if (CurOffs < CurLayObj->first) {
9905 uint64_t padding = CurLayObj->first - CurOffs;
9906 // FIXME: There doesn't seem to be a way to indicate in the encoding that
9907 // packing/alignment of members is different that normal, in which case
9908 // the encoding will be out-of-sync with the real layout.
9909 // If the runtime switches to just consider the size of types without
9910 // taking into account alignment, we could make padding explicit in the
9911 // encoding (e.g. using arrays of chars). The encoding strings would be
9912 // longer then though.
9913 CurOffs += padding;
9914 }
9915#endif
9916
9917 NamedDecl *dcl = CurLayObj->second;
9918 if (!dcl)
9919 break; // reached end of structure.
9920
9921 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
9922 // We expand the bases without their virtual bases since those are going
9923 // in the initial structure. Note that this differs from gcc which
9924 // expands virtual bases each time one is encountered in the hierarchy,
9925 // making the encoding type bigger than it really is.
9926 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
9927 NotEncodedT);
9928 assert(!base->isEmpty());
9929#ifndef NDEBUG
9930 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
9931#endif
9932 } else {
9933 const auto *field = cast<FieldDecl>(dcl);
9934 if (FD) {
9935 S += '"';
9936 S += field->getNameAsString();
9937 S += '"';
9938 }
9939
9940 if (field->isBitField()) {
9941 EncodeBitField(this, S, field->getType(), field);
9942#ifndef NDEBUG
9943 CurOffs += field->getBitWidthValue();
9944#endif
9945 } else {
9946 QualType qt = field->getType();
9948 getObjCEncodingForTypeImpl(
9949 qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(),
9950 FD, NotEncodedT);
9951#ifndef NDEBUG
9952 CurOffs += getTypeSize(field->getType());
9953#endif
9954 }
9955 }
9956 }
9957}
9958
9960 std::string& S) const {
9961 if (QT & Decl::OBJC_TQ_In)
9962 S += 'n';
9963 if (QT & Decl::OBJC_TQ_Inout)
9964 S += 'N';
9965 if (QT & Decl::OBJC_TQ_Out)
9966 S += 'o';
9967 if (QT & Decl::OBJC_TQ_Bycopy)
9968 S += 'O';
9969 if (QT & Decl::OBJC_TQ_Byref)
9970 S += 'R';
9971 if (QT & Decl::OBJC_TQ_Oneway)
9972 S += 'V';
9973}
9974
9976 if (!ObjCIdDecl) {
9979 ObjCIdDecl = buildImplicitTypedef(T, "id");
9980 }
9981 return ObjCIdDecl;
9982}
9983
9985 if (!ObjCSelDecl) {
9987 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
9988 }
9989 return ObjCSelDecl;
9990}
9991
9993 if (!ObjCClassDecl) {
9996 ObjCClassDecl = buildImplicitTypedef(T, "Class");
9997 }
9998 return ObjCClassDecl;
9999}
10000
10002 if (!ObjCProtocolClassDecl) {
10003 ObjCProtocolClassDecl
10006 &Idents.get("Protocol"),
10007 /*typeParamList=*/nullptr,
10008 /*PrevDecl=*/nullptr,
10009 SourceLocation(), true);
10010 }
10011
10012 return ObjCProtocolClassDecl;
10013}
10014
10016 if (!getLangOpts().PointerAuthObjcInterfaceSel)
10017 return PointerAuthQualifier();
10019 getLangOpts().PointerAuthObjcInterfaceSelKey,
10020 /*isAddressDiscriminated=*/true, SelPointerConstantDiscriminator,
10022 /*isIsaPointer=*/false,
10023 /*authenticatesNullValues=*/false);
10024}
10025
10026//===----------------------------------------------------------------------===//
10027// __builtin_va_list Construction Functions
10028//===----------------------------------------------------------------------===//
10029
10031 StringRef Name) {
10032 // typedef char* __builtin[_ms]_va_list;
10033 QualType T = Context->getPointerType(Context->CharTy);
10034 return Context->buildImplicitTypedef(T, Name);
10035}
10036
10038 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
10039}
10040
10042 // typedef char *__builtin_zos_va_list[2];
10043 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 2);
10044 QualType T = Context->getPointerType(Context->CharTy);
10045 QualType ArrayType = Context->getConstantArrayType(
10046 T, Size, nullptr, ArraySizeModifier::Normal, 0);
10047 return Context->buildImplicitTypedef(ArrayType, "__builtin_zos_va_list");
10048}
10049
10051 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
10052}
10053
10055 // typedef void* __builtin_va_list;
10056 QualType T = Context->getPointerType(Context->VoidTy);
10057 return Context->buildImplicitTypedef(T, "__builtin_va_list");
10058}
10059
10060static TypedefDecl *
10062 // struct __va_list
10063 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
10064 if (Context->getLangOpts().CPlusPlus) {
10065 // namespace std { struct __va_list {
10066 auto *NS = NamespaceDecl::Create(
10067 const_cast<ASTContext &>(*Context), Context->getTranslationUnitDecl(),
10068 /*Inline=*/false, SourceLocation(), SourceLocation(),
10069 &Context->Idents.get("std"),
10070 /*PrevDecl=*/nullptr, /*Nested=*/false);
10071 NS->setImplicit();
10073 }
10074
10075 VaListTagDecl->startDefinition();
10076
10077 const size_t NumFields = 5;
10078 QualType FieldTypes[NumFields];
10079 const char *FieldNames[NumFields];
10080
10081 // void *__stack;
10082 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
10083 FieldNames[0] = "__stack";
10084
10085 // void *__gr_top;
10086 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
10087 FieldNames[1] = "__gr_top";
10088
10089 // void *__vr_top;
10090 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10091 FieldNames[2] = "__vr_top";
10092
10093 // int __gr_offs;
10094 FieldTypes[3] = Context->IntTy;
10095 FieldNames[3] = "__gr_offs";
10096
10097 // int __vr_offs;
10098 FieldTypes[4] = Context->IntTy;
10099 FieldNames[4] = "__vr_offs";
10100
10101 // Create fields
10102 for (unsigned i = 0; i < NumFields; ++i) {
10103 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10107 &Context->Idents.get(FieldNames[i]),
10108 FieldTypes[i], /*TInfo=*/nullptr,
10109 /*BitWidth=*/nullptr,
10110 /*Mutable=*/false,
10111 ICIS_NoInit);
10112 Field->setAccess(AS_public);
10113 VaListTagDecl->addDecl(Field);
10114 }
10115 VaListTagDecl->completeDefinition();
10116 Context->VaListTagDecl = VaListTagDecl;
10117 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10118
10119 // } __builtin_va_list;
10120 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
10121}
10122
10124 // typedef struct __va_list_tag {
10126
10127 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10128 VaListTagDecl->startDefinition();
10129
10130 const size_t NumFields = 5;
10131 QualType FieldTypes[NumFields];
10132 const char *FieldNames[NumFields];
10133
10134 // unsigned char gpr;
10135 FieldTypes[0] = Context->UnsignedCharTy;
10136 FieldNames[0] = "gpr";
10137
10138 // unsigned char fpr;
10139 FieldTypes[1] = Context->UnsignedCharTy;
10140 FieldNames[1] = "fpr";
10141
10142 // unsigned short reserved;
10143 FieldTypes[2] = Context->UnsignedShortTy;
10144 FieldNames[2] = "reserved";
10145
10146 // void* overflow_arg_area;
10147 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
10148 FieldNames[3] = "overflow_arg_area";
10149
10150 // void* reg_save_area;
10151 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
10152 FieldNames[4] = "reg_save_area";
10153
10154 // Create fields
10155 for (unsigned i = 0; i < NumFields; ++i) {
10156 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
10159 &Context->Idents.get(FieldNames[i]),
10160 FieldTypes[i], /*TInfo=*/nullptr,
10161 /*BitWidth=*/nullptr,
10162 /*Mutable=*/false,
10163 ICIS_NoInit);
10164 Field->setAccess(AS_public);
10165 VaListTagDecl->addDecl(Field);
10166 }
10167 VaListTagDecl->completeDefinition();
10168 Context->VaListTagDecl = VaListTagDecl;
10169 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10170
10171 // } __va_list_tag;
10172 TypedefDecl *VaListTagTypedefDecl =
10173 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
10174
10175 QualType VaListTagTypedefType =
10176 Context->getTypedefType(ElaboratedTypeKeyword::None,
10177 /*Qualifier=*/std::nullopt, VaListTagTypedefDecl);
10178
10179 // typedef __va_list_tag __builtin_va_list[1];
10180 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10181 QualType VaListTagArrayType = Context->getConstantArrayType(
10182 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
10183 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10184}
10185
10186static TypedefDecl *
10188 // struct __va_list_tag {
10190 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10191 VaListTagDecl->startDefinition();
10192
10193 const size_t NumFields = 4;
10194 QualType FieldTypes[NumFields];
10195 const char *FieldNames[NumFields];
10196
10197 // unsigned gp_offset;
10198 FieldTypes[0] = Context->UnsignedIntTy;
10199 FieldNames[0] = "gp_offset";
10200
10201 // unsigned fp_offset;
10202 FieldTypes[1] = Context->UnsignedIntTy;
10203 FieldNames[1] = "fp_offset";
10204
10205 // void* overflow_arg_area;
10206 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10207 FieldNames[2] = "overflow_arg_area";
10208
10209 // void* reg_save_area;
10210 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
10211 FieldNames[3] = "reg_save_area";
10212
10213 // Create fields
10214 for (unsigned i = 0; i < NumFields; ++i) {
10215 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10219 &Context->Idents.get(FieldNames[i]),
10220 FieldTypes[i], /*TInfo=*/nullptr,
10221 /*BitWidth=*/nullptr,
10222 /*Mutable=*/false,
10223 ICIS_NoInit);
10224 Field->setAccess(AS_public);
10225 VaListTagDecl->addDecl(Field);
10226 }
10227 VaListTagDecl->completeDefinition();
10228 Context->VaListTagDecl = VaListTagDecl;
10229 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10230
10231 // };
10232
10233 // typedef struct __va_list_tag __builtin_va_list[1];
10234 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10235 QualType VaListTagArrayType = Context->getConstantArrayType(
10236 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
10237 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10238}
10239
10240static TypedefDecl *
10242 // struct __va_list
10243 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
10244 if (Context->getLangOpts().CPlusPlus) {
10245 // namespace std { struct __va_list {
10246 NamespaceDecl *NS;
10247 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
10248 Context->getTranslationUnitDecl(),
10249 /*Inline=*/false, SourceLocation(),
10250 SourceLocation(), &Context->Idents.get("std"),
10251 /*PrevDecl=*/nullptr, /*Nested=*/false);
10252 NS->setImplicit();
10253 VaListDecl->setDeclContext(NS);
10254 }
10255
10256 VaListDecl->startDefinition();
10257
10258 // void * __ap;
10259 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10260 VaListDecl,
10263 &Context->Idents.get("__ap"),
10264 Context->getPointerType(Context->VoidTy),
10265 /*TInfo=*/nullptr,
10266 /*BitWidth=*/nullptr,
10267 /*Mutable=*/false,
10268 ICIS_NoInit);
10269 Field->setAccess(AS_public);
10270 VaListDecl->addDecl(Field);
10271
10272 // };
10273 VaListDecl->completeDefinition();
10274 Context->VaListTagDecl = VaListDecl;
10275
10276 // typedef struct __va_list __builtin_va_list;
10277 CanQualType T = Context->getCanonicalTagType(VaListDecl);
10278 return Context->buildImplicitTypedef(T, "__builtin_va_list");
10279}
10280
10281static TypedefDecl *
10283 // struct __va_list_tag {
10285 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10286 VaListTagDecl->startDefinition();
10287
10288 const size_t NumFields = 4;
10289 QualType FieldTypes[NumFields];
10290 const char *FieldNames[NumFields];
10291
10292 // long __gpr;
10293 FieldTypes[0] = Context->LongTy;
10294 FieldNames[0] = "__gpr";
10295
10296 // long __fpr;
10297 FieldTypes[1] = Context->LongTy;
10298 FieldNames[1] = "__fpr";
10299
10300 // void *__overflow_arg_area;
10301 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10302 FieldNames[2] = "__overflow_arg_area";
10303
10304 // void *__reg_save_area;
10305 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
10306 FieldNames[3] = "__reg_save_area";
10307
10308 // Create fields
10309 for (unsigned i = 0; i < NumFields; ++i) {
10310 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10314 &Context->Idents.get(FieldNames[i]),
10315 FieldTypes[i], /*TInfo=*/nullptr,
10316 /*BitWidth=*/nullptr,
10317 /*Mutable=*/false,
10318 ICIS_NoInit);
10319 Field->setAccess(AS_public);
10320 VaListTagDecl->addDecl(Field);
10321 }
10322 VaListTagDecl->completeDefinition();
10323 Context->VaListTagDecl = VaListTagDecl;
10324 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10325
10326 // };
10327
10328 // typedef __va_list_tag __builtin_va_list[1];
10329 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10330 QualType VaListTagArrayType = Context->getConstantArrayType(
10331 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
10332
10333 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10334}
10335
10337 // typedef struct __va_list_tag {
10339 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10340 VaListTagDecl->startDefinition();
10341
10342 const size_t NumFields = 3;
10343 QualType FieldTypes[NumFields];
10344 const char *FieldNames[NumFields];
10345
10346 // void *CurrentSavedRegisterArea;
10347 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
10348 FieldNames[0] = "__current_saved_reg_area_pointer";
10349
10350 // void *SavedRegAreaEnd;
10351 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
10352 FieldNames[1] = "__saved_reg_area_end_pointer";
10353
10354 // void *OverflowArea;
10355 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10356 FieldNames[2] = "__overflow_area_pointer";
10357
10358 // Create fields
10359 for (unsigned i = 0; i < NumFields; ++i) {
10361 const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(),
10362 SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i],
10363 /*TInfo=*/nullptr,
10364 /*BitWidth=*/nullptr,
10365 /*Mutable=*/false, ICIS_NoInit);
10366 Field->setAccess(AS_public);
10367 VaListTagDecl->addDecl(Field);
10368 }
10369 VaListTagDecl->completeDefinition();
10370 Context->VaListTagDecl = VaListTagDecl;
10371 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10372
10373 // } __va_list_tag;
10374 TypedefDecl *VaListTagTypedefDecl =
10375 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
10376
10377 QualType VaListTagTypedefType =
10378 Context->getTypedefType(ElaboratedTypeKeyword::None,
10379 /*Qualifier=*/std::nullopt, VaListTagTypedefDecl);
10380
10381 // typedef __va_list_tag __builtin_va_list[1];
10382 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10383 QualType VaListTagArrayType = Context->getConstantArrayType(
10384 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
10385
10386 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10387}
10388
10389static TypedefDecl *
10391 // typedef struct __va_list_tag {
10392 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10393
10394 VaListTagDecl->startDefinition();
10395
10396 // int* __va_stk;
10397 // int* __va_reg;
10398 // int __va_ndx;
10399 constexpr size_t NumFields = 3;
10400 QualType FieldTypes[NumFields] = {Context->getPointerType(Context->IntTy),
10401 Context->getPointerType(Context->IntTy),
10402 Context->IntTy};
10403 const char *FieldNames[NumFields] = {"__va_stk", "__va_reg", "__va_ndx"};
10404
10405 // Create fields
10406 for (unsigned i = 0; i < NumFields; ++i) {
10409 &Context->Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
10410 /*BitWidth=*/nullptr,
10411 /*Mutable=*/false, ICIS_NoInit);
10412 Field->setAccess(AS_public);
10413 VaListTagDecl->addDecl(Field);
10414 }
10415 VaListTagDecl->completeDefinition();
10416 Context->VaListTagDecl = VaListTagDecl;
10417 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10418
10419 // } __va_list_tag;
10420 TypedefDecl *VaListTagTypedefDecl =
10421 Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
10422
10423 return VaListTagTypedefDecl;
10424}
10425
10428 switch (Kind) {
10430 return CreateCharPtrBuiltinVaListDecl(Context);
10432 return CreateVoidPtrBuiltinVaListDecl(Context);
10434 return CreateAArch64ABIBuiltinVaListDecl(Context);
10436 return CreatePowerABIBuiltinVaListDecl(Context);
10438 return CreateX86_64ABIBuiltinVaListDecl(Context);
10440 return CreateAAPCSABIBuiltinVaListDecl(Context);
10442 return CreateSystemZBuiltinVaListDecl(Context);
10444 return CreateHexagonBuiltinVaListDecl(Context);
10446 return CreateXtensaABIBuiltinVaListDecl(Context);
10447 }
10448
10449 llvm_unreachable("Unhandled __builtin_va_list type kind");
10450}
10451
10453 if (!BuiltinVaListDecl) {
10454 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
10455 assert(BuiltinVaListDecl->isImplicit());
10456 }
10457
10458 return BuiltinVaListDecl;
10459}
10460
10462 // Force the creation of VaListTagDecl by building the __builtin_va_list
10463 // declaration.
10464 if (!VaListTagDecl)
10465 (void)getBuiltinVaListDecl();
10466
10467 return VaListTagDecl;
10468}
10469
10471 if (!BuiltinMSVaListDecl)
10472 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
10473
10474 return BuiltinMSVaListDecl;
10475}
10476
10478 if (!BuiltinZOSVaListDecl)
10479 BuiltinZOSVaListDecl = CreateZOSVaListDecl(this);
10480
10481 return BuiltinZOSVaListDecl;
10482}
10483
10485 // Allow redecl custom type checking builtin for HLSL.
10486 if (LangOpts.HLSL && FD->getBuiltinID() != Builtin::NotBuiltin &&
10487 BuiltinInfo.hasCustomTypechecking(FD->getBuiltinID()))
10488 return true;
10489 // Allow redecl custom type checking builtin for SPIR-V.
10490 if (getTargetInfo().getTriple().isSPIROrSPIRV() &&
10491 BuiltinInfo.isTSBuiltin(FD->getBuiltinID()) &&
10492 BuiltinInfo.hasCustomTypechecking(FD->getBuiltinID()))
10493 return true;
10494 return BuiltinInfo.canBeRedeclared(FD->getBuiltinID());
10495}
10496
10498 assert(ObjCConstantStringType.isNull() &&
10499 "'NSConstantString' type already set!");
10500
10501 ObjCConstantStringType = getObjCInterfaceType(Decl);
10502}
10503
10504/// Retrieve the template name that corresponds to a non-empty
10505/// lookup.
10508 UnresolvedSetIterator End) const {
10509 unsigned size = End - Begin;
10510 assert(size > 1 && "set is not overloaded!");
10511
10512 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
10513 size * sizeof(FunctionTemplateDecl*));
10514 auto *OT = new (memory) OverloadedTemplateStorage(size);
10515
10516 NamedDecl **Storage = OT->getStorage();
10517 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
10518 NamedDecl *D = *I;
10519 assert(isa<FunctionTemplateDecl>(D) ||
10523 *Storage++ = D;
10524 }
10525
10526 return TemplateName(OT);
10527}
10528
10529/// Retrieve a template name representing an unqualified-id that has been
10530/// assumed to name a template for ADL purposes.
10532 auto *OT = new (*this) AssumedTemplateStorage(Name);
10533 return TemplateName(OT);
10534}
10535
10536/// Retrieve the template name that represents a qualified
10537/// template name such as \c std::vector.
10539 bool TemplateKeyword,
10540 TemplateName Template) const {
10541 assert(Template.getKind() == TemplateName::Template ||
10543
10544 if (Template.getAsTemplateDecl()->getKind() == Decl::TemplateTemplateParm) {
10545 assert(!Qualifier && "unexpected qualified template template parameter");
10546 assert(TemplateKeyword == false);
10547 return Template;
10548 }
10549
10550 // FIXME: Canonicalization?
10551 llvm::FoldingSetNodeID ID;
10552 QualifiedTemplateName::Profile(ID, Qualifier, TemplateKeyword, Template);
10553
10554 llvm::FoldingSetInsertToken Token;
10555 QualifiedTemplateName *QTN = QualifiedTemplateNames.lookup(ID, Token);
10556 if (!QTN) {
10557 QTN = new (*this, alignof(QualifiedTemplateName))
10558 QualifiedTemplateName(Qualifier, TemplateKeyword, Template);
10559 QualifiedTemplateNames.insert(QTN, Token);
10560 }
10561
10562 return TemplateName(QTN);
10563}
10564
10565/// Retrieve the template name that represents a dependent
10566/// template name such as \c MetaFun::template operator+.
10569 llvm::FoldingSetNodeID ID;
10570 S.Profile(ID);
10571
10572 llvm::FoldingSetInsertToken Token;
10573 if (DependentTemplateName *QTN = DependentTemplateNames.lookup(ID, Token))
10574 return TemplateName(QTN);
10575
10577 new (*this, alignof(DependentTemplateName)) DependentTemplateName(S);
10578 DependentTemplateNames.insert(QTN, Token);
10579 return TemplateName(QTN);
10580}
10581
10583 Decl *AssociatedDecl,
10584 unsigned Index,
10586 bool Final) const {
10587 llvm::FoldingSetNodeID ID;
10588 SubstTemplateTemplateParmStorage::Profile(ID, Replacement, AssociatedDecl,
10589 Index, PackIndex, Final);
10590
10591 llvm::FoldingSetInsertToken Token;
10593 SubstTemplateTemplateParms.lookup(ID, Token);
10594
10595 if (!subst) {
10596 subst = new (*this) SubstTemplateTemplateParmStorage(
10597 Replacement, AssociatedDecl, Index, PackIndex, Final);
10598 SubstTemplateTemplateParms.insert(subst, Token);
10599 }
10600
10601 return TemplateName(subst);
10602}
10603
10606 Decl *AssociatedDecl,
10607 unsigned Index, bool Final) const {
10608 auto &Self = const_cast<ASTContext &>(*this);
10609 llvm::FoldingSetNodeID ID;
10611 AssociatedDecl, Index, Final);
10612
10613 llvm::FoldingSetInsertToken Token;
10615 SubstTemplateTemplateParmPacks.lookup(ID, Token);
10616
10617 if (!Subst) {
10618 Subst = new (*this) SubstTemplateTemplateParmPackStorage(
10619 ArgPack.pack_elements(), AssociatedDecl, Index, Final);
10620 SubstTemplateTemplateParmPacks.insert(Subst, Token);
10621 }
10622
10623 return TemplateName(Subst);
10624}
10625
10626/// Retrieve the template name that represents a template name
10627/// deduced from a specialization.
10630 DefaultArguments DefaultArgs) const {
10631 if (!DefaultArgs)
10632 return Underlying;
10633
10634 llvm::FoldingSetNodeID ID;
10635 DeducedTemplateStorage::Profile(ID, *this, Underlying, DefaultArgs);
10636
10637 llvm::FoldingSetInsertToken Token;
10638 DeducedTemplateStorage *DTS = DeducedTemplates.lookup(ID, Token);
10639 if (!DTS) {
10640 void *Mem = Allocate(sizeof(DeducedTemplateStorage) +
10641 sizeof(TemplateArgument) * DefaultArgs.Args.size(),
10642 alignof(DeducedTemplateStorage));
10643 DTS = new (Mem) DeducedTemplateStorage(Underlying, DefaultArgs);
10644 DeducedTemplates.insert(DTS, Token);
10645 }
10646 return TemplateName(DTS);
10647}
10648
10650 TemplateName Pattern, Expr *IndexExpr, bool FullySubstituted,
10651 ArrayRef<TemplateName> Expansions) const {
10652 auto &Self = const_cast<ASTContext &>(*this);
10653 llvm::FoldingSetNodeID ID;
10654 PackIndexingTemplateStorage::Profile(ID, Self, Pattern, IndexExpr,
10655 FullySubstituted, Expansions);
10656
10657 llvm::FoldingSetInsertToken Token;
10658 PackIndexingTemplateStorage *PI = PackIndexingTemplates.lookup(ID, Token);
10659 if (!PI) {
10660 void *Mem =
10661 Allocate(PackIndexingTemplateStorage::totalSizeToAlloc<TemplateName>(
10662 Expansions.size()),
10664 PI = new (Mem) PackIndexingTemplateStorage(Pattern, IndexExpr,
10665 FullySubstituted, Expansions);
10666 PackIndexingTemplates.insert(PI, Token);
10667 }
10668 return TemplateName(PI);
10669}
10670
10671/// getFromTargetType - Given one of the integer types provided by
10672/// TargetInfo, produce the corresponding type. The unsigned @p Type
10673/// is actually a value of type @c TargetInfo::IntType.
10674CanQualType ASTContext::getFromTargetType(unsigned Type) const {
10675 switch (Type) {
10676 case TargetInfo::NoInt: return {};
10679 case TargetInfo::SignedShort: return ShortTy;
10681 case TargetInfo::SignedInt: return IntTy;
10683 case TargetInfo::SignedLong: return LongTy;
10687 }
10688
10689 llvm_unreachable("Unhandled TargetInfo::IntType value");
10690}
10691
10692//===----------------------------------------------------------------------===//
10693// Type Predicates.
10694//===----------------------------------------------------------------------===//
10695
10696/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
10697/// garbage collection attribute.
10698///
10700 if (getLangOpts().getGC() == LangOptions::NonGC)
10701 return Qualifiers::GCNone;
10702
10703 assert(getLangOpts().ObjC);
10704 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
10705
10706 // Default behaviour under objective-C's gc is for ObjC pointers
10707 // (or pointers to them) be treated as though they were declared
10708 // as __strong.
10709 if (GCAttrs == Qualifiers::GCNone) {
10711 return Qualifiers::Strong;
10712 else if (Ty->isPointerType())
10714 } else {
10715 // It's not valid to set GC attributes on anything that isn't a
10716 // pointer.
10717#ifndef NDEBUG
10719 while (const auto *AT = dyn_cast<ArrayType>(CT))
10720 CT = AT->getElementType();
10721 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
10722#endif
10723 }
10724 return GCAttrs;
10725}
10726
10727//===----------------------------------------------------------------------===//
10728// Type Compatibility Testing
10729//===----------------------------------------------------------------------===//
10730
10731/// areCompatVectorTypes - Return true if the two specified vector types are
10732/// compatible.
10733static bool areCompatVectorTypes(const VectorType *LHS,
10734 const VectorType *RHS) {
10735 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10736 return LHS->getElementType() == RHS->getElementType() &&
10737 LHS->getNumElements() == RHS->getNumElements();
10738}
10739
10740/// areCompatMatrixTypes - Return true if the two specified matrix types are
10741/// compatible.
10743 const ConstantMatrixType *RHS) {
10744 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10745 return LHS->getElementType() == RHS->getElementType() &&
10746 LHS->getNumRows() == RHS->getNumRows() &&
10747 LHS->getNumColumns() == RHS->getNumColumns();
10748}
10749
10751 QualType SecondVec) {
10752 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
10753 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
10754
10755 if (hasSameUnqualifiedType(FirstVec, SecondVec))
10756 return true;
10757
10758 // Treat Neon vector types and most AltiVec vector types as if they are the
10759 // equivalent GCC vector types.
10760 const auto *First = FirstVec->castAs<VectorType>();
10761 const auto *Second = SecondVec->castAs<VectorType>();
10762 if (First->getNumElements() == Second->getNumElements() &&
10763 hasSameType(First->getElementType(), Second->getElementType()) &&
10764 First->getVectorKind() != VectorKind::AltiVecPixel &&
10765 First->getVectorKind() != VectorKind::AltiVecBool &&
10768 First->getVectorKind() != VectorKind::SveFixedLengthData &&
10769 First->getVectorKind() != VectorKind::SveFixedLengthPredicate &&
10772 First->getVectorKind() != VectorKind::RVVFixedLengthData &&
10774 First->getVectorKind() != VectorKind::RVVFixedLengthMask &&
10776 First->getVectorKind() != VectorKind::RVVFixedLengthMask_1 &&
10778 First->getVectorKind() != VectorKind::RVVFixedLengthMask_2 &&
10780 First->getVectorKind() != VectorKind::RVVFixedLengthMask_4 &&
10782 return true;
10783
10784 // In OpenCL, treat half and _Float16 vector types as compatible.
10785 if (getLangOpts().OpenCL &&
10786 First->getNumElements() == Second->getNumElements()) {
10787 QualType FirstElt = First->getElementType();
10788 QualType SecondElt = Second->getElementType();
10789
10790 if ((FirstElt->isFloat16Type() && SecondElt->isHalfType()) ||
10791 (FirstElt->isHalfType() && SecondElt->isFloat16Type())) {
10792 if (First->getVectorKind() != VectorKind::AltiVecPixel &&
10793 First->getVectorKind() != VectorKind::AltiVecBool &&
10796 return true;
10797 }
10798 }
10799 return false;
10800}
10801
10807
10810 const auto *LHSOBT = LHS->getAs<OverflowBehaviorType>();
10811 const auto *RHSOBT = RHS->getAs<OverflowBehaviorType>();
10812
10813 if (!LHSOBT && !RHSOBT)
10815
10816 if (LHSOBT && RHSOBT) {
10817 if (LHSOBT->getBehaviorKind() != RHSOBT->getBehaviorKind())
10820 }
10821
10822 QualType LHSUnderlying = LHSOBT ? LHSOBT->desugar() : LHS;
10823 QualType RHSUnderlying = RHSOBT ? RHSOBT->desugar() : RHS;
10824
10825 if (RHSOBT && !LHSOBT) {
10826 if (LHSUnderlying->isIntegerType() && RHSUnderlying->isIntegerType())
10828 }
10829
10831}
10832
10833/// getRVVTypeSize - Return RVV vector register size.
10834static uint64_t getRVVTypeSize(ASTContext &Context, const BuiltinType *Ty) {
10835 assert(Ty->isRVVVLSBuiltinType() && "Invalid RVV Type");
10836 auto VScale = Context.getTargetInfo().getVScaleRange(
10837 Context.getLangOpts(), TargetInfo::ArmStreamingKind::NotStreaming);
10838 if (!VScale)
10839 return 0;
10840
10841 ASTContext::BuiltinVectorTypeInfo Info = Context.getBuiltinVectorTypeInfo(Ty);
10842
10843 uint64_t EltSize = Context.getTypeSize(Info.ElementType);
10844 if (Info.ElementType == Context.BoolTy)
10845 EltSize = 1;
10846
10847 uint64_t MinElts = Info.EC.getKnownMinValue();
10848 return VScale->first * MinElts * EltSize;
10849}
10850
10852 QualType SecondType) {
10853 assert(
10854 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10855 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10856 "Expected RVV builtin type and vector type!");
10857
10858 auto IsValidCast = [this](QualType FirstType, QualType SecondType) {
10859 if (const auto *BT = FirstType->getAs<BuiltinType>()) {
10860 if (const auto *VT = SecondType->getAs<VectorType>()) {
10861 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask) {
10863 return FirstType->isRVVVLSBuiltinType() &&
10864 Info.ElementType == BoolTy &&
10865 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)));
10866 }
10867 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_1) {
10869 return FirstType->isRVVVLSBuiltinType() &&
10870 Info.ElementType == BoolTy &&
10871 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT) * 8));
10872 }
10873 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_2) {
10875 return FirstType->isRVVVLSBuiltinType() &&
10876 Info.ElementType == BoolTy &&
10877 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)) * 4);
10878 }
10879 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_4) {
10881 return FirstType->isRVVVLSBuiltinType() &&
10882 Info.ElementType == BoolTy &&
10883 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)) * 2);
10884 }
10885 if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
10886 VT->getVectorKind() == VectorKind::Generic)
10887 return FirstType->isRVVVLSBuiltinType() &&
10888 getTypeSize(SecondType) == getRVVTypeSize(*this, BT) &&
10889 hasSameType(VT->getElementType(),
10890 getBuiltinVectorTypeInfo(BT).ElementType);
10891 }
10892 }
10893 return false;
10894 };
10895
10896 return IsValidCast(FirstType, SecondType) ||
10897 IsValidCast(SecondType, FirstType);
10898}
10899
10901 QualType SecondType) {
10902 assert(
10903 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10904 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10905 "Expected RVV builtin type and vector type!");
10906
10907 auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) {
10908 const auto *BT = FirstType->getAs<BuiltinType>();
10909 if (!BT)
10910 return false;
10911
10912 if (!BT->isRVVVLSBuiltinType())
10913 return false;
10914
10915 const auto *VecTy = SecondType->getAs<VectorType>();
10916 if (VecTy && VecTy->getVectorKind() == VectorKind::Generic) {
10918 getLangOpts().getLaxVectorConversions();
10919
10920 // If __riscv_v_fixed_vlen != N do not allow vector lax conversion.
10921 if (getTypeSize(SecondType) != getRVVTypeSize(*this, BT))
10922 return false;
10923
10924 // If -flax-vector-conversions=all is specified, the types are
10925 // certainly compatible.
10927 return true;
10928
10929 // If -flax-vector-conversions=integer is specified, the types are
10930 // compatible if the elements are integer types.
10932 return VecTy->getElementType().getCanonicalType()->isIntegerType() &&
10933 FirstType->getRVVEltType(*this)->isIntegerType();
10934 }
10935
10936 return false;
10937 };
10938
10939 return IsLaxCompatible(FirstType, SecondType) ||
10940 IsLaxCompatible(SecondType, FirstType);
10941}
10942
10944 while (true) {
10945 // __strong id
10946 if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) {
10947 if (Attr->getAttrKind() == attr::ObjCOwnership)
10948 return true;
10949
10950 Ty = Attr->getModifiedType();
10951
10952 // X *__strong (...)
10953 } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) {
10954 Ty = Paren->getInnerType();
10955
10956 // We do not want to look through typedefs, typeof(expr),
10957 // typeof(type), or any other way that the type is somehow
10958 // abstracted.
10959 } else {
10960 return false;
10961 }
10962 }
10963}
10964
10965//===----------------------------------------------------------------------===//
10966// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
10967//===----------------------------------------------------------------------===//
10968
10969/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
10970/// inheritance hierarchy of 'rProto'.
10971bool
10973 ObjCProtocolDecl *rProto) const {
10974 if (declaresSameEntity(lProto, rProto))
10975 return true;
10976 for (auto *PI : rProto->protocols())
10977 if (ProtocolCompatibleWithProtocol(lProto, PI))
10978 return true;
10979 return false;
10980}
10981
10982/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
10983/// Class<pr1, ...>.
10985 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) {
10986 for (auto *lhsProto : lhs->quals()) {
10987 bool match = false;
10988 for (auto *rhsProto : rhs->quals()) {
10989 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
10990 match = true;
10991 break;
10992 }
10993 }
10994 if (!match)
10995 return false;
10996 }
10997 return true;
10998}
10999
11000/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
11001/// ObjCQualifiedIDType.
11003 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs,
11004 bool compare) {
11005 // Allow id<P..> and an 'id' in all cases.
11006 if (lhs->isObjCIdType() || rhs->isObjCIdType())
11007 return true;
11008
11009 // Don't allow id<P..> to convert to Class or Class<P..> in either direction.
11010 if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() ||
11012 return false;
11013
11014 if (lhs->isObjCQualifiedIdType()) {
11015 if (rhs->qual_empty()) {
11016 // If the RHS is a unqualified interface pointer "NSString*",
11017 // make sure we check the class hierarchy.
11018 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
11019 for (auto *I : lhs->quals()) {
11020 // when comparing an id<P> on lhs with a static type on rhs,
11021 // see if static class implements all of id's protocols, directly or
11022 // through its super class and categories.
11023 if (!rhsID->ClassImplementsProtocol(I, true))
11024 return false;
11025 }
11026 }
11027 // If there are no qualifiers and no interface, we have an 'id'.
11028 return true;
11029 }
11030 // Both the right and left sides have qualifiers.
11031 for (auto *lhsProto : lhs->quals()) {
11032 bool match = false;
11033
11034 // when comparing an id<P> on lhs with a static type on rhs,
11035 // see if static class implements all of id's protocols, directly or
11036 // through its super class and categories.
11037 for (auto *rhsProto : rhs->quals()) {
11038 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
11039 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
11040 match = true;
11041 break;
11042 }
11043 }
11044 // If the RHS is a qualified interface pointer "NSString<P>*",
11045 // make sure we check the class hierarchy.
11046 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
11047 for (auto *I : lhs->quals()) {
11048 // when comparing an id<P> on lhs with a static type on rhs,
11049 // see if static class implements all of id's protocols, directly or
11050 // through its super class and categories.
11051 if (rhsID->ClassImplementsProtocol(I, true)) {
11052 match = true;
11053 break;
11054 }
11055 }
11056 }
11057 if (!match)
11058 return false;
11059 }
11060
11061 return true;
11062 }
11063
11064 assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>");
11065
11066 if (lhs->getInterfaceType()) {
11067 // If both the right and left sides have qualifiers.
11068 for (auto *lhsProto : lhs->quals()) {
11069 bool match = false;
11070
11071 // when comparing an id<P> on rhs with a static type on lhs,
11072 // see if static class implements all of id's protocols, directly or
11073 // through its super class and categories.
11074 // First, lhs protocols in the qualifier list must be found, direct
11075 // or indirect in rhs's qualifier list or it is a mismatch.
11076 for (auto *rhsProto : rhs->quals()) {
11077 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
11078 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
11079 match = true;
11080 break;
11081 }
11082 }
11083 if (!match)
11084 return false;
11085 }
11086
11087 // Static class's protocols, or its super class or category protocols
11088 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
11089 if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) {
11090 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
11091 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
11092 // This is rather dubious but matches gcc's behavior. If lhs has
11093 // no type qualifier and its class has no static protocol(s)
11094 // assume that it is mismatch.
11095 if (LHSInheritedProtocols.empty() && lhs->qual_empty())
11096 return false;
11097 for (auto *lhsProto : LHSInheritedProtocols) {
11098 bool match = false;
11099 for (auto *rhsProto : rhs->quals()) {
11100 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
11101 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
11102 match = true;
11103 break;
11104 }
11105 }
11106 if (!match)
11107 return false;
11108 }
11109 }
11110 return true;
11111 }
11112 return false;
11113}
11114
11115/// canAssignObjCInterfaces - Return true if the two interface types are
11116/// compatible for assignment from RHS to LHS. This handles validation of any
11117/// protocol qualifiers on the LHS or RHS.
11119 const ObjCObjectPointerType *RHSOPT) {
11120 const ObjCObjectType* LHS = LHSOPT->getObjectType();
11121 const ObjCObjectType* RHS = RHSOPT->getObjectType();
11122
11123 // If either type represents the built-in 'id' type, return true.
11124 if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId())
11125 return true;
11126
11127 // Function object that propagates a successful result or handles
11128 // __kindof types.
11129 auto finish = [&](bool succeeded) -> bool {
11130 if (succeeded)
11131 return true;
11132
11133 if (!RHS->isKindOfType())
11134 return false;
11135
11136 // Strip off __kindof and protocol qualifiers, then check whether
11137 // we can assign the other way.
11139 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
11140 };
11141
11142 // Casts from or to id<P> are allowed when the other side has compatible
11143 // protocols.
11144 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
11145 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false));
11146 }
11147
11148 // Verify protocol compatibility for casts from Class<P1> to Class<P2>.
11149 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
11150 return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT));
11151 }
11152
11153 // Casts from Class to Class<Foo>, or vice-versa, are allowed.
11154 if (LHS->isObjCClass() && RHS->isObjCClass()) {
11155 return true;
11156 }
11157
11158 // If we have 2 user-defined types, fall into that path.
11159 if (LHS->getInterface() && RHS->getInterface()) {
11160 return finish(canAssignObjCInterfaces(LHS, RHS));
11161 }
11162
11163 return false;
11164}
11165
11166/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
11167/// for providing type-safety for objective-c pointers used to pass/return
11168/// arguments in block literals. When passed as arguments, passing 'A*' where
11169/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
11170/// not OK. For the return type, the opposite is not OK.
11172 const ObjCObjectPointerType *LHSOPT,
11173 const ObjCObjectPointerType *RHSOPT,
11174 bool BlockReturnType) {
11175
11176 // Function object that propagates a successful result or handles
11177 // __kindof types.
11178 auto finish = [&](bool succeeded) -> bool {
11179 if (succeeded)
11180 return true;
11181
11182 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
11183 if (!Expected->isKindOfType())
11184 return false;
11185
11186 // Strip off __kindof and protocol qualifiers, then check whether
11187 // we can assign the other way.
11189 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
11190 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
11191 BlockReturnType);
11192 };
11193
11194 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
11195 return true;
11196
11197 if (LHSOPT->isObjCBuiltinType()) {
11198 return finish(RHSOPT->isObjCBuiltinType() ||
11199 RHSOPT->isObjCQualifiedIdType());
11200 }
11201
11202 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) {
11203 if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking)
11204 // Use for block parameters previous type checking for compatibility.
11205 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false) ||
11206 // Or corrected type checking as in non-compat mode.
11207 (!BlockReturnType &&
11208 ObjCQualifiedIdTypesAreCompatible(RHSOPT, LHSOPT, false)));
11209 else
11211 (BlockReturnType ? LHSOPT : RHSOPT),
11212 (BlockReturnType ? RHSOPT : LHSOPT), false));
11213 }
11214
11215 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
11216 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
11217 if (LHS && RHS) { // We have 2 user-defined types.
11218 if (LHS != RHS) {
11219 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
11220 return finish(BlockReturnType);
11221 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
11222 return finish(!BlockReturnType);
11223 }
11224 else
11225 return true;
11226 }
11227 return false;
11228}
11229
11230/// Comparison routine for Objective-C protocols to be used with
11231/// llvm::array_pod_sort.
11233 ObjCProtocolDecl * const *rhs) {
11234 return (*lhs)->getName().compare((*rhs)->getName());
11235}
11236
11237/// getIntersectionOfProtocols - This routine finds the intersection of set
11238/// of protocols inherited from two distinct objective-c pointer objects with
11239/// the given common base.
11240/// It is used to build composite qualifier list of the composite type of
11241/// the conditional expression involving two objective-c pointer objects.
11242static
11244 const ObjCInterfaceDecl *CommonBase,
11245 const ObjCObjectPointerType *LHSOPT,
11246 const ObjCObjectPointerType *RHSOPT,
11247 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
11248
11249 const ObjCObjectType* LHS = LHSOPT->getObjectType();
11250 const ObjCObjectType* RHS = RHSOPT->getObjectType();
11251 assert(LHS->getInterface() && "LHS must have an interface base");
11252 assert(RHS->getInterface() && "RHS must have an interface base");
11253
11254 // Add all of the protocols for the LHS.
11256
11257 // Start with the protocol qualifiers.
11258 for (auto *proto : LHS->quals()) {
11259 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
11260 }
11261
11262 // Also add the protocols associated with the LHS interface.
11263 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
11264
11265 // Add all of the protocols for the RHS.
11267
11268 // Start with the protocol qualifiers.
11269 for (auto *proto : RHS->quals()) {
11270 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
11271 }
11272
11273 // Also add the protocols associated with the RHS interface.
11274 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
11275
11276 // Compute the intersection of the collected protocol sets.
11277 for (auto *proto : LHSProtocolSet) {
11278 if (RHSProtocolSet.count(proto))
11279 IntersectionSet.push_back(proto);
11280 }
11281
11282 // Compute the set of protocols that is implied by either the common type or
11283 // the protocols within the intersection.
11285 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
11286
11287 // Remove any implied protocols from the list of inherited protocols.
11288 if (!ImpliedProtocols.empty()) {
11289 llvm::erase_if(IntersectionSet, [&](ObjCProtocolDecl *proto) -> bool {
11290 return ImpliedProtocols.contains(proto);
11291 });
11292 }
11293
11294 // Sort the remaining protocols by name.
11295 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
11297}
11298
11299/// Determine whether the first type is a subtype of the second.
11301 QualType rhs) {
11302 // Common case: two object pointers.
11303 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
11304 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
11305 if (lhsOPT && rhsOPT)
11306 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
11307
11308 // Two block pointers.
11309 const auto *lhsBlock = lhs->getAs<BlockPointerType>();
11310 const auto *rhsBlock = rhs->getAs<BlockPointerType>();
11311 if (lhsBlock && rhsBlock)
11312 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
11313
11314 // If either is an unqualified 'id' and the other is a block, it's
11315 // acceptable.
11316 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
11317 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
11318 return true;
11319
11320 return false;
11321}
11322
11323// Check that the given Objective-C type argument lists are equivalent.
11325 const ObjCInterfaceDecl *iface,
11326 ArrayRef<QualType> lhsArgs,
11327 ArrayRef<QualType> rhsArgs,
11328 bool stripKindOf) {
11329 if (lhsArgs.size() != rhsArgs.size())
11330 return false;
11331
11332 ObjCTypeParamList *typeParams = iface->getTypeParamList();
11333 if (!typeParams)
11334 return false;
11335
11336 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
11337 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
11338 continue;
11339
11340 switch (typeParams->begin()[i]->getVariance()) {
11342 if (!stripKindOf ||
11343 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
11344 rhsArgs[i].stripObjCKindOfType(ctx))) {
11345 return false;
11346 }
11347 break;
11348
11350 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
11351 return false;
11352 break;
11353
11355 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
11356 return false;
11357 break;
11358 }
11359 }
11360
11361 return true;
11362}
11363
11365 const ObjCObjectPointerType *Lptr,
11366 const ObjCObjectPointerType *Rptr) {
11367 const ObjCObjectType *LHS = Lptr->getObjectType();
11368 const ObjCObjectType *RHS = Rptr->getObjectType();
11369 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
11370 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
11371
11372 if (!LDecl || !RDecl)
11373 return {};
11374
11375 // When either LHS or RHS is a kindof type, we should return a kindof type.
11376 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
11377 // kindof(A).
11378 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
11379
11380 // Follow the left-hand side up the class hierarchy until we either hit a
11381 // root or find the RHS. Record the ancestors in case we don't find it.
11382 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
11383 LHSAncestors;
11384 while (true) {
11385 // Record this ancestor. We'll need this if the common type isn't in the
11386 // path from the LHS to the root.
11387 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
11388
11389 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
11390 // Get the type arguments.
11391 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
11392 bool anyChanges = false;
11393 if (LHS->isSpecialized() && RHS->isSpecialized()) {
11394 // Both have type arguments, compare them.
11395 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
11396 LHS->getTypeArgs(), RHS->getTypeArgs(),
11397 /*stripKindOf=*/true))
11398 return {};
11399 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
11400 // If only one has type arguments, the result will not have type
11401 // arguments.
11402 LHSTypeArgs = {};
11403 anyChanges = true;
11404 }
11405
11406 // Compute the intersection of protocols.
11408 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
11409 Protocols);
11410 if (!Protocols.empty())
11411 anyChanges = true;
11412
11413 // If anything in the LHS will have changed, build a new result type.
11414 // If we need to return a kindof type but LHS is not a kindof type, we
11415 // build a new result type.
11416 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
11417 QualType Result = getObjCInterfaceType(LHS->getInterface());
11418 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
11419 anyKindOf || LHS->isKindOfType());
11421 }
11422
11423 return getObjCObjectPointerType(QualType(LHS, 0));
11424 }
11425
11426 // Find the superclass.
11427 QualType LHSSuperType = LHS->getSuperClassType();
11428 if (LHSSuperType.isNull())
11429 break;
11430
11431 LHS = LHSSuperType->castAs<ObjCObjectType>();
11432 }
11433
11434 // We didn't find anything by following the LHS to its root; now check
11435 // the RHS against the cached set of ancestors.
11436 while (true) {
11437 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
11438 if (KnownLHS != LHSAncestors.end()) {
11439 LHS = KnownLHS->second;
11440
11441 // Get the type arguments.
11442 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
11443 bool anyChanges = false;
11444 if (LHS->isSpecialized() && RHS->isSpecialized()) {
11445 // Both have type arguments, compare them.
11446 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
11447 LHS->getTypeArgs(), RHS->getTypeArgs(),
11448 /*stripKindOf=*/true))
11449 return {};
11450 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
11451 // If only one has type arguments, the result will not have type
11452 // arguments.
11453 RHSTypeArgs = {};
11454 anyChanges = true;
11455 }
11456
11457 // Compute the intersection of protocols.
11459 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
11460 Protocols);
11461 if (!Protocols.empty())
11462 anyChanges = true;
11463
11464 // If we need to return a kindof type but RHS is not a kindof type, we
11465 // build a new result type.
11466 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
11467 QualType Result = getObjCInterfaceType(RHS->getInterface());
11468 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
11469 anyKindOf || RHS->isKindOfType());
11471 }
11472
11473 return getObjCObjectPointerType(QualType(RHS, 0));
11474 }
11475
11476 // Find the superclass of the RHS.
11477 QualType RHSSuperType = RHS->getSuperClassType();
11478 if (RHSSuperType.isNull())
11479 break;
11480
11481 RHS = RHSSuperType->castAs<ObjCObjectType>();
11482 }
11483
11484 return {};
11485}
11486
11488 const ObjCObjectType *RHS) {
11489 assert(LHS->getInterface() && "LHS is not an interface type");
11490 assert(RHS->getInterface() && "RHS is not an interface type");
11491
11492 // Verify that the base decls are compatible: the RHS must be a subclass of
11493 // the LHS.
11494 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
11495 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
11496 if (!IsSuperClass)
11497 return false;
11498
11499 // If the LHS has protocol qualifiers, determine whether all of them are
11500 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
11501 // LHS).
11502 if (LHS->getNumProtocols() > 0) {
11503 // OK if conversion of LHS to SuperClass results in narrowing of types
11504 // ; i.e., SuperClass may implement at least one of the protocols
11505 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
11506 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
11507 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
11508 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
11509 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
11510 // qualifiers.
11511 for (auto *RHSPI : RHS->quals())
11512 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
11513 // If there is no protocols associated with RHS, it is not a match.
11514 if (SuperClassInheritedProtocols.empty())
11515 return false;
11516
11517 for (const auto *LHSProto : LHS->quals()) {
11518 bool SuperImplementsProtocol = false;
11519 for (auto *SuperClassProto : SuperClassInheritedProtocols)
11520 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
11521 SuperImplementsProtocol = true;
11522 break;
11523 }
11524 if (!SuperImplementsProtocol)
11525 return false;
11526 }
11527 }
11528
11529 // If the LHS is specialized, we may need to check type arguments.
11530 if (LHS->isSpecialized()) {
11531 // Follow the superclass chain until we've matched the LHS class in the
11532 // hierarchy. This substitutes type arguments through.
11533 const ObjCObjectType *RHSSuper = RHS;
11534 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
11535 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
11536
11537 // If the RHS is specializd, compare type arguments.
11538 if (RHSSuper->isSpecialized() &&
11539 !sameObjCTypeArgs(*this, LHS->getInterface(),
11540 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
11541 /*stripKindOf=*/true)) {
11542 return false;
11543 }
11544 }
11545
11546 return true;
11547}
11548
11550 // get the "pointed to" types
11551 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
11552 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
11553
11554 if (!LHSOPT || !RHSOPT)
11555 return false;
11556
11557 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
11558 canAssignObjCInterfaces(RHSOPT, LHSOPT);
11559}
11560
11563 getObjCObjectPointerType(To)->castAs<ObjCObjectPointerType>(),
11564 getObjCObjectPointerType(From)->castAs<ObjCObjectPointerType>());
11565}
11566
11567/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
11568/// both shall have the identically qualified version of a compatible type.
11569/// C99 6.2.7p1: Two types have compatible types if their types are the
11570/// same. See 6.7.[2,3,5] for additional rules.
11572 bool CompareUnqualified) {
11573 if (getLangOpts().CPlusPlus)
11574 return hasSameType(LHS, RHS);
11575
11576 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
11577}
11578
11580 return typesAreCompatible(LHS, RHS);
11581}
11582
11584 return !mergeTypes(LHS, RHS, true).isNull();
11585}
11586
11587/// mergeTransparentUnionType - if T is a transparent union type and a member
11588/// of T is compatible with SubType, return the merged type, else return
11589/// QualType()
11591 bool OfBlockPointer,
11592 bool Unqualified) {
11593 if (const RecordType *UT = T->getAsUnionType()) {
11594 RecordDecl *UD = UT->getDecl()->getMostRecentDecl();
11595 if (UD->hasAttr<TransparentUnionAttr>()) {
11596 for (const auto *I : UD->fields()) {
11597 QualType ET = I->getType().getUnqualifiedType();
11598 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
11599 if (!MT.isNull())
11600 return MT;
11601 }
11602 }
11603 }
11604
11605 return {};
11606}
11607
11608/// mergeFunctionParameterTypes - merge two types which appear as function
11609/// parameter types
11611 bool OfBlockPointer,
11612 bool Unqualified) {
11613 // GNU extension: two types are compatible if they appear as a function
11614 // argument, one of the types is a transparent union type and the other
11615 // type is compatible with a union member
11616 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
11617 Unqualified);
11618 if (!lmerge.isNull())
11619 return lmerge;
11620
11621 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
11622 Unqualified);
11623 if (!rmerge.isNull())
11624 return rmerge;
11625
11626 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
11627}
11628
11630 bool OfBlockPointer, bool Unqualified,
11631 bool AllowCXX,
11632 bool IsConditionalOperator) {
11633 const auto *lbase = lhs->castAs<FunctionType>();
11634 const auto *rbase = rhs->castAs<FunctionType>();
11635 const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
11636 const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
11637 bool allLTypes = true;
11638 bool allRTypes = true;
11639
11640 // Check return type
11641 QualType retType;
11642 if (OfBlockPointer) {
11643 QualType RHS = rbase->getReturnType();
11644 QualType LHS = lbase->getReturnType();
11645 bool UnqualifiedResult = Unqualified;
11646 if (!UnqualifiedResult)
11647 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
11648 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
11649 }
11650 else
11651 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
11652 Unqualified);
11653 if (retType.isNull())
11654 return {};
11655
11656 if (Unqualified)
11657 retType = retType.getUnqualifiedType();
11658
11659 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
11660 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
11661 if (Unqualified) {
11662 LRetType = LRetType.getUnqualifiedType();
11663 RRetType = RRetType.getUnqualifiedType();
11664 }
11665
11666 if (getCanonicalType(retType) != LRetType)
11667 allLTypes = false;
11668 if (getCanonicalType(retType) != RRetType)
11669 allRTypes = false;
11670
11671 // FIXME: double check this
11672 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
11673 // rbase->getRegParmAttr() != 0 &&
11674 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
11675 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
11676 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
11677
11678 // Compatible functions must have compatible calling conventions
11679 if (lbaseInfo.getCC() != rbaseInfo.getCC())
11680 return {};
11681
11682 // Regparm is part of the calling convention.
11683 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
11684 return {};
11685 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
11686 return {};
11687
11688 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
11689 return {};
11690 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
11691 return {};
11692 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
11693 return {};
11694
11695 // When merging declarations, it's common for supplemental information like
11696 // attributes to only be present in one of the declarations, and we generally
11697 // want type merging to preserve the union of information. So a merged
11698 // function type should be noreturn if it was noreturn in *either* operand
11699 // type.
11700 //
11701 // But for the conditional operator, this is backwards. The result of the
11702 // operator could be either operand, and its type should conservatively
11703 // reflect that. So a function type in a composite type is noreturn only
11704 // if it's noreturn in *both* operand types.
11705 //
11706 // Arguably, noreturn is a kind of subtype, and the conditional operator
11707 // ought to produce the most specific common supertype of its operand types.
11708 // That would differ from this rule in contravariant positions. However,
11709 // neither C nor C++ generally uses this kind of subtype reasoning. Also,
11710 // as a practical matter, it would only affect C code that does abstraction of
11711 // higher-order functions (taking noreturn callbacks!), which is uncommon to
11712 // say the least. So we use the simpler rule.
11713 bool NoReturn = IsConditionalOperator
11714 ? lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn()
11715 : lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
11716 if (lbaseInfo.getNoReturn() != NoReturn)
11717 allLTypes = false;
11718 if (rbaseInfo.getNoReturn() != NoReturn)
11719 allRTypes = false;
11720
11721 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
11722
11723 std::optional<FunctionEffectSet> MergedFX;
11724
11725 if (lproto && rproto) { // two C99 style function prototypes
11726 assert((AllowCXX ||
11727 (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) &&
11728 "C++ shouldn't be here");
11729 // Compatible functions must have the same number of parameters
11730 if (lproto->getNumParams() != rproto->getNumParams())
11731 return {};
11732
11733 // Variadic and non-variadic functions aren't compatible
11734 if (lproto->isVariadic() != rproto->isVariadic())
11735 return {};
11736
11737 if (lproto->getMethodQuals() != rproto->getMethodQuals())
11738 return {};
11739
11740 // Function protos with different 'cfi_salt' values aren't compatible.
11741 if (lproto->getExtraAttributeInfo().CFISalt !=
11742 rproto->getExtraAttributeInfo().CFISalt)
11743 return {};
11744
11745 // Function effects are handled similarly to noreturn, see above.
11746 FunctionEffectsRef LHSFX = lproto->getFunctionEffects();
11747 FunctionEffectsRef RHSFX = rproto->getFunctionEffects();
11748 if (LHSFX != RHSFX) {
11749 if (IsConditionalOperator)
11750 MergedFX = FunctionEffectSet::getIntersection(LHSFX, RHSFX);
11751 else {
11753 MergedFX = FunctionEffectSet::getUnion(LHSFX, RHSFX, Errs);
11754 // Here we're discarding a possible error due to conflicts in the effect
11755 // sets. But we're not in a context where we can report it. The
11756 // operation does however guarantee maintenance of invariants.
11757 }
11758 if (*MergedFX != LHSFX)
11759 allLTypes = false;
11760 if (*MergedFX != RHSFX)
11761 allRTypes = false;
11762 }
11763
11765 bool canUseLeft, canUseRight;
11766 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
11767 newParamInfos))
11768 return {};
11769
11770 if (!canUseLeft)
11771 allLTypes = false;
11772 if (!canUseRight)
11773 allRTypes = false;
11774
11775 // Check parameter type compatibility
11777 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
11778 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
11779 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
11781 lParamType, rParamType, OfBlockPointer, Unqualified);
11782 if (paramType.isNull())
11783 return {};
11784
11785 if (Unqualified)
11786 paramType = paramType.getUnqualifiedType();
11787
11788 types.push_back(paramType);
11789 if (Unqualified) {
11790 lParamType = lParamType.getUnqualifiedType();
11791 rParamType = rParamType.getUnqualifiedType();
11792 }
11793
11794 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
11795 allLTypes = false;
11796 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
11797 allRTypes = false;
11798 }
11799
11800 if (allLTypes) return lhs;
11801 if (allRTypes) return rhs;
11802
11803 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
11804 EPI.ExtInfo = einfo;
11805 EPI.ExtParameterInfos =
11806 newParamInfos.empty() ? nullptr : newParamInfos.data();
11807 if (MergedFX)
11808 EPI.FunctionEffects = *MergedFX;
11809 return getFunctionType(retType, types, EPI);
11810 }
11811
11812 if (lproto) allRTypes = false;
11813 if (rproto) allLTypes = false;
11814
11815 const FunctionProtoType *proto = lproto ? lproto : rproto;
11816 if (proto) {
11817 assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here");
11818 if (proto->isVariadic())
11819 return {};
11820 // Check that the types are compatible with the types that
11821 // would result from default argument promotions (C99 6.7.5.3p15).
11822 // The only types actually affected are promotable integer
11823 // types and floats, which would be passed as a different
11824 // type depending on whether the prototype is visible.
11825 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
11826 QualType paramTy = proto->getParamType(i);
11827
11828 // Look at the converted type of enum types, since that is the type used
11829 // to pass enum values.
11830 if (const auto *ED = paramTy->getAsEnumDecl()) {
11831 paramTy = ED->getIntegerType();
11832 if (paramTy.isNull())
11833 return {};
11834 }
11835
11836 if (isPromotableIntegerType(paramTy) ||
11837 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
11838 return {};
11839 }
11840
11841 if (allLTypes) return lhs;
11842 if (allRTypes) return rhs;
11843
11845 EPI.ExtInfo = einfo;
11846 if (MergedFX)
11847 EPI.FunctionEffects = *MergedFX;
11848 return getFunctionType(retType, proto->getParamTypes(), EPI);
11849 }
11850
11851 if (allLTypes) return lhs;
11852 if (allRTypes) return rhs;
11853 return getFunctionNoProtoType(retType, einfo);
11854}
11855
11856/// Given that we have an enum type and a non-enum type, try to merge them.
11857static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
11858 QualType other, bool isBlockReturnType) {
11859 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
11860 // a signed integer type, or an unsigned integer type.
11861 // Compatibility is based on the underlying type, not the promotion
11862 // type.
11863 QualType underlyingType =
11864 ET->getDecl()->getDefinitionOrSelf()->getIntegerType();
11865 if (underlyingType.isNull())
11866 return {};
11867 if (Context.hasSameType(underlyingType, other))
11868 return other;
11869
11870 // In block return types, we're more permissive and accept any
11871 // integral type of the same size.
11872 if (isBlockReturnType && other->isIntegerType() &&
11873 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
11874 return other;
11875
11876 return {};
11877}
11878
11880 // C17 and earlier and C++ disallow two tag definitions within the same TU
11881 // from being compatible.
11882 if (LangOpts.CPlusPlus || !LangOpts.C23)
11883 return {};
11884
11885 // Nameless tags are comparable only within outer definitions. At the top
11886 // level they are not comparable.
11887 const TagDecl *LTagD = LHS->castAsTagDecl(), *RTagD = RHS->castAsTagDecl();
11888 if (!LTagD->getIdentifier() || !RTagD->getIdentifier())
11889 return {};
11890
11891 // C23, on the other hand, requires the members to be "the same enough", so
11892 // we use a structural equivalence check.
11895 getLangOpts(), *this, *this, NonEquivalentDecls,
11896 StructuralEquivalenceKind::Default, /*StrictTypeSpelling=*/false,
11897 /*Complain=*/false, /*ErrorOnTagTypeMismatch=*/true);
11898 return Ctx.IsEquivalent(LHS, RHS) ? LHS : QualType{};
11899}
11900
11902 QualType LHS, QualType RHS, bool OfBlockPointer, bool Unqualified,
11903 bool BlockReturnType, bool IsConditionalOperator) {
11904 const auto *LHSOBT = LHS->getAs<OverflowBehaviorType>();
11905 const auto *RHSOBT = RHS->getAs<OverflowBehaviorType>();
11906
11907 if (!LHSOBT && !RHSOBT)
11908 return std::nullopt;
11909
11910 if (LHSOBT) {
11911 if (RHSOBT) {
11912 if (LHSOBT->getBehaviorKind() != RHSOBT->getBehaviorKind())
11913 return QualType();
11914
11915 QualType MergedUnderlying = mergeTypes(
11916 LHSOBT->getUnderlyingType(), RHSOBT->getUnderlyingType(),
11917 OfBlockPointer, Unqualified, BlockReturnType, IsConditionalOperator);
11918
11919 if (MergedUnderlying.isNull())
11920 return QualType();
11921
11922 if (getCanonicalType(LHSOBT) == getCanonicalType(RHSOBT)) {
11923 if (LHSOBT->getUnderlyingType() == RHSOBT->getUnderlyingType())
11924 return getCommonSugaredType(LHS, RHS);
11926 LHSOBT->getBehaviorKind(),
11927 getCanonicalType(LHSOBT->getUnderlyingType()));
11928 }
11929
11930 // For different underlying types that successfully merge, wrap the
11931 // merged underlying type with the common overflow behavior
11932 return getOverflowBehaviorType(LHSOBT->getBehaviorKind(),
11933 MergedUnderlying);
11934 }
11935 return mergeTypes(LHSOBT->getUnderlyingType(), RHS, OfBlockPointer,
11936 Unqualified, BlockReturnType, IsConditionalOperator);
11937 }
11938
11939 return mergeTypes(LHS, RHSOBT->getUnderlyingType(), OfBlockPointer,
11940 Unqualified, BlockReturnType, IsConditionalOperator);
11941}
11942
11943QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
11944 bool Unqualified, bool BlockReturnType,
11945 bool IsConditionalOperator) {
11946 // For C++ we will not reach this code with reference types (see below),
11947 // for OpenMP variant call overloading we might.
11948 //
11949 // C++ [expr]: If an expression initially has the type "reference to T", the
11950 // type is adjusted to "T" prior to any further analysis, the expression
11951 // designates the object or function denoted by the reference, and the
11952 // expression is an lvalue unless the reference is an rvalue reference and
11953 // the expression is a function call (possibly inside parentheses).
11954 auto *LHSRefTy = LHS->getAs<ReferenceType>();
11955 auto *RHSRefTy = RHS->getAs<ReferenceType>();
11956 if (LangOpts.OpenMP && LHSRefTy && RHSRefTy &&
11957 LHS->getTypeClass() == RHS->getTypeClass())
11958 return mergeTypes(LHSRefTy->getPointeeType(), RHSRefTy->getPointeeType(),
11959 OfBlockPointer, Unqualified, BlockReturnType);
11960 if (LHSRefTy || RHSRefTy)
11961 return {};
11962
11963 if (std::optional<QualType> MergedOBT =
11964 tryMergeOverflowBehaviorTypes(LHS, RHS, OfBlockPointer, Unqualified,
11965 BlockReturnType, IsConditionalOperator))
11966 return *MergedOBT;
11967
11968 if (Unqualified) {
11969 LHS = LHS.getUnqualifiedType();
11970 RHS = RHS.getUnqualifiedType();
11971 }
11972
11973 QualType LHSCan = getCanonicalType(LHS),
11974 RHSCan = getCanonicalType(RHS);
11975
11976 // If two types are identical, they are compatible.
11977 if (LHSCan == RHSCan)
11978 return LHS;
11979
11980 // If the qualifiers are different, the types aren't compatible... mostly.
11981 Qualifiers LQuals = LHSCan.getLocalQualifiers();
11982 Qualifiers RQuals = RHSCan.getLocalQualifiers();
11983 if (LQuals != RQuals) {
11984 // If any of these qualifiers are different, we have a type
11985 // mismatch.
11986 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
11987 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
11988 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
11989 !LQuals.getPointerAuth().isEquivalent(RQuals.getPointerAuth()) ||
11990 LQuals.hasUnaligned() != RQuals.hasUnaligned())
11991 return {};
11992
11993 // Exactly one GC qualifier difference is allowed: __strong is
11994 // okay if the other type has no GC qualifier but is an Objective
11995 // C object pointer (i.e. implicitly strong by default). We fix
11996 // this by pretending that the unqualified type was actually
11997 // qualified __strong.
11998 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
11999 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
12000 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
12001
12002 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
12003 return {};
12004
12005 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
12007 }
12008 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
12010 }
12011 return {};
12012 }
12013
12014 // Okay, qualifiers are equal.
12015
12016 Type::TypeClass LHSClass = LHSCan->getTypeClass();
12017 Type::TypeClass RHSClass = RHSCan->getTypeClass();
12018
12019 // We want to consider the two function types to be the same for these
12020 // comparisons, just force one to the other.
12021 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
12022 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
12023
12024 // Same as above for arrays
12025 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
12026 LHSClass = Type::ConstantArray;
12027 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
12028 RHSClass = Type::ConstantArray;
12029
12030 // ObjCInterfaces are just specialized ObjCObjects.
12031 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
12032 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
12033
12034 // Canonicalize ExtVector -> Vector.
12035 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
12036 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
12037
12038 // If the canonical type classes don't match.
12039 if (LHSClass != RHSClass) {
12040 // Note that we only have special rules for turning block enum
12041 // returns into block int returns, not vice-versa.
12042 if (const auto *ETy = LHS->getAsCanonical<EnumType>()) {
12043 return mergeEnumWithInteger(*this, ETy, RHS, false);
12044 }
12045 if (const EnumType *ETy = RHS->getAsCanonical<EnumType>()) {
12046 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
12047 }
12048 // allow block pointer type to match an 'id' type.
12049 if (OfBlockPointer && !BlockReturnType) {
12050 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
12051 return LHS;
12052 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
12053 return RHS;
12054 }
12055 // Allow __auto_type to match anything; it merges to the type with more
12056 // information.
12057 if (const auto *AT = LHS->getAs<AutoType>()) {
12058 if (!AT->isDeduced() && AT->isGNUAutoType())
12059 return RHS;
12060 }
12061 if (const auto *AT = RHS->getAs<AutoType>()) {
12062 if (!AT->isDeduced() && AT->isGNUAutoType())
12063 return LHS;
12064 }
12065 return {};
12066 }
12067
12068 // The canonical type classes match.
12069 switch (LHSClass) {
12070#define TYPE(Class, Base)
12071#define ABSTRACT_TYPE(Class, Base)
12072#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
12073#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
12074#define DEPENDENT_TYPE(Class, Base) case Type::Class:
12075#include "clang/AST/TypeNodes.inc"
12076 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
12077
12078 case Type::Auto:
12079 case Type::DeducedTemplateSpecialization:
12080 case Type::LValueReference:
12081 case Type::RValueReference:
12082 case Type::MemberPointer:
12083 llvm_unreachable("C++ should never be in mergeTypes");
12084
12085 case Type::ObjCInterface:
12086 case Type::IncompleteArray:
12087 case Type::VariableArray:
12088 case Type::FunctionProto:
12089 case Type::ExtVector:
12090 case Type::OverflowBehavior:
12091 llvm_unreachable("Types are eliminated above");
12092
12093 case Type::Pointer:
12094 {
12095 // Merge two pointer types, while trying to preserve typedef info
12096 QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType();
12097 QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType();
12098 if (Unqualified) {
12099 LHSPointee = LHSPointee.getUnqualifiedType();
12100 RHSPointee = RHSPointee.getUnqualifiedType();
12101 }
12102 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
12103 Unqualified);
12104 if (ResultType.isNull())
12105 return {};
12106 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
12107 return LHS;
12108 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
12109 return RHS;
12110 return getPointerType(ResultType);
12111 }
12112 case Type::BlockPointer:
12113 {
12114 // Merge two block pointer types, while trying to preserve typedef info
12115 QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType();
12116 QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType();
12117 if (Unqualified) {
12118 LHSPointee = LHSPointee.getUnqualifiedType();
12119 RHSPointee = RHSPointee.getUnqualifiedType();
12120 }
12121 if (getLangOpts().OpenCL) {
12122 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
12123 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
12124 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
12125 // 6.12.5) thus the following check is asymmetric.
12126 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual, *this))
12127 return {};
12128 LHSPteeQual.removeAddressSpace();
12129 RHSPteeQual.removeAddressSpace();
12130 LHSPointee =
12131 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
12132 RHSPointee =
12133 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
12134 }
12135 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
12136 Unqualified);
12137 if (ResultType.isNull())
12138 return {};
12139 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
12140 return LHS;
12141 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
12142 return RHS;
12143 return getBlockPointerType(ResultType);
12144 }
12145 case Type::Atomic:
12146 {
12147 // Merge two pointer types, while trying to preserve typedef info
12148 QualType LHSValue = LHS->castAs<AtomicType>()->getValueType();
12149 QualType RHSValue = RHS->castAs<AtomicType>()->getValueType();
12150 if (Unqualified) {
12151 LHSValue = LHSValue.getUnqualifiedType();
12152 RHSValue = RHSValue.getUnqualifiedType();
12153 }
12154 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
12155 Unqualified);
12156 if (ResultType.isNull())
12157 return {};
12158 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
12159 return LHS;
12160 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
12161 return RHS;
12162 return getAtomicType(ResultType);
12163 }
12164 case Type::ConstantArray:
12165 {
12166 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
12167 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
12168 if (LCAT && RCAT && RCAT->getZExtSize() != LCAT->getZExtSize())
12169 return {};
12170
12171 QualType LHSElem = getAsArrayType(LHS)->getElementType();
12172 QualType RHSElem = getAsArrayType(RHS)->getElementType();
12173 if (Unqualified) {
12174 LHSElem = LHSElem.getUnqualifiedType();
12175 RHSElem = RHSElem.getUnqualifiedType();
12176 }
12177
12178 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
12179 if (ResultType.isNull())
12180 return {};
12181
12182 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
12183 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
12184
12185 // If either side is a variable array, and both are complete, check whether
12186 // the current dimension is definite.
12187 if (LVAT || RVAT) {
12188 auto SizeFetch = [this](const VariableArrayType* VAT,
12189 const ConstantArrayType* CAT)
12190 -> std::pair<bool,llvm::APInt> {
12191 if (VAT) {
12192 std::optional<llvm::APSInt> TheInt;
12193 Expr *E = VAT->getSizeExpr();
12194 if (E && (TheInt = E->getIntegerConstantExpr(*this)))
12195 return std::make_pair(true, *TheInt);
12196 return std::make_pair(false, llvm::APSInt());
12197 }
12198 if (CAT)
12199 return std::make_pair(true, CAT->getSize());
12200 return std::make_pair(false, llvm::APInt());
12201 };
12202
12203 bool HaveLSize, HaveRSize;
12204 llvm::APInt LSize, RSize;
12205 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
12206 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
12207 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
12208 return {}; // Definite, but unequal, array dimension
12209 }
12210
12211 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
12212 return LHS;
12213 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
12214 return RHS;
12215 if (LCAT)
12216 return getConstantArrayType(ResultType, LCAT->getSize(),
12217 LCAT->getSizeExpr(), ArraySizeModifier(), 0);
12218 if (RCAT)
12219 return getConstantArrayType(ResultType, RCAT->getSize(),
12220 RCAT->getSizeExpr(), ArraySizeModifier(), 0);
12221 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
12222 return LHS;
12223 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
12224 return RHS;
12225 if (LVAT) {
12226 // FIXME: This isn't correct! But tricky to implement because
12227 // the array's size has to be the size of LHS, but the type
12228 // has to be different.
12229 return LHS;
12230 }
12231 if (RVAT) {
12232 // FIXME: This isn't correct! But tricky to implement because
12233 // the array's size has to be the size of RHS, but the type
12234 // has to be different.
12235 return RHS;
12236 }
12237 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
12238 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
12239 return getIncompleteArrayType(ResultType, ArraySizeModifier(), 0);
12240 }
12241 case Type::FunctionNoProto:
12242 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified,
12243 /*AllowCXX=*/false, IsConditionalOperator);
12244 case Type::Record:
12245 case Type::Enum:
12246 return mergeTagDefinitions(LHS, RHS);
12247 case Type::Builtin:
12248 // Only exactly equal builtin types are compatible, which is tested above.
12249 return {};
12250 case Type::Complex:
12251 // Distinct complex types are incompatible.
12252 return {};
12253 case Type::Vector:
12254 // FIXME: The merged type should be an ExtVector!
12255 if (areCompatVectorTypes(LHSCan->castAs<VectorType>(),
12256 RHSCan->castAs<VectorType>()))
12257 return LHS;
12258 return {};
12259 case Type::ConstantMatrix:
12261 RHSCan->castAs<ConstantMatrixType>()))
12262 return LHS;
12263 return {};
12264 case Type::ObjCObject: {
12265 // Check if the types are assignment compatible.
12266 // FIXME: This should be type compatibility, e.g. whether
12267 // "LHS x; RHS x;" at global scope is legal.
12269 RHS->castAs<ObjCObjectType>()))
12270 return LHS;
12271 return {};
12272 }
12273 case Type::ObjCObjectPointer:
12274 if (OfBlockPointer) {
12277 RHS->castAs<ObjCObjectPointerType>(), BlockReturnType))
12278 return LHS;
12279 return {};
12280 }
12283 return LHS;
12284 return {};
12285 case Type::Pipe:
12286 assert(LHS != RHS &&
12287 "Equivalent pipe types should have already been handled!");
12288 return {};
12289 case Type::ArrayParameter:
12290 assert(LHS != RHS &&
12291 "Equivalent ArrayParameter types should have already been handled!");
12292 return {};
12293 case Type::BitInt: {
12294 // Merge two bit-precise int types, while trying to preserve typedef info.
12295 bool LHSUnsigned = LHS->castAs<BitIntType>()->isUnsigned();
12296 bool RHSUnsigned = RHS->castAs<BitIntType>()->isUnsigned();
12297 unsigned LHSBits = LHS->castAs<BitIntType>()->getNumBits();
12298 unsigned RHSBits = RHS->castAs<BitIntType>()->getNumBits();
12299
12300 // Like unsigned/int, shouldn't have a type if they don't match.
12301 if (LHSUnsigned != RHSUnsigned)
12302 return {};
12303
12304 if (LHSBits != RHSBits)
12305 return {};
12306 return LHS;
12307 }
12308 case Type::HLSLAttributedResource: {
12309 const HLSLAttributedResourceType *LHSTy =
12310 LHS->castAs<HLSLAttributedResourceType>();
12311 const HLSLAttributedResourceType *RHSTy =
12312 RHS->castAs<HLSLAttributedResourceType>();
12313 assert(LHSTy->getWrappedType() == RHSTy->getWrappedType() &&
12314 LHSTy->getWrappedType()->isHLSLResourceType() &&
12315 "HLSLAttributedResourceType should always wrap __hlsl_resource_t");
12316
12317 if (LHSTy->getAttrs() == RHSTy->getAttrs() &&
12318 LHSTy->getContainedType() == RHSTy->getContainedType())
12319 return LHS;
12320 return {};
12321 }
12322 case Type::HLSLInlineSpirv:
12323 const HLSLInlineSpirvType *LHSTy = LHS->castAs<HLSLInlineSpirvType>();
12324 const HLSLInlineSpirvType *RHSTy = RHS->castAs<HLSLInlineSpirvType>();
12325
12326 if (LHSTy->getOpcode() == RHSTy->getOpcode() &&
12327 LHSTy->getSize() == RHSTy->getSize() &&
12328 LHSTy->getAlignment() == RHSTy->getAlignment()) {
12329 for (size_t I = 0; I < LHSTy->getOperands().size(); I++)
12330 if (LHSTy->getOperands()[I] != RHSTy->getOperands()[I])
12331 return {};
12332
12333 return LHS;
12334 }
12335 return {};
12336 }
12337
12338 llvm_unreachable("Invalid Type::Class!");
12339}
12340
12342 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
12343 bool &CanUseFirst, bool &CanUseSecond,
12345 assert(NewParamInfos.empty() && "param info list not empty");
12346 CanUseFirst = CanUseSecond = true;
12347 bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
12348 bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
12349
12350 // Fast path: if the first type doesn't have ext parameter infos,
12351 // we match if and only if the second type also doesn't have them.
12352 if (!FirstHasInfo && !SecondHasInfo)
12353 return true;
12354
12355 bool NeedParamInfo = false;
12356 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
12357 : SecondFnType->getExtParameterInfos().size();
12358
12359 for (size_t I = 0; I < E; ++I) {
12360 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
12361 if (FirstHasInfo)
12362 FirstParam = FirstFnType->getExtParameterInfo(I);
12363 if (SecondHasInfo)
12364 SecondParam = SecondFnType->getExtParameterInfo(I);
12365
12366 // Cannot merge unless everything except the noescape flag matches.
12367 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
12368 return false;
12369
12370 bool FirstNoEscape = FirstParam.isNoEscape();
12371 bool SecondNoEscape = SecondParam.isNoEscape();
12372 bool IsNoEscape = FirstNoEscape && SecondNoEscape;
12373 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
12374 if (NewParamInfos.back().getOpaqueValue())
12375 NeedParamInfo = true;
12376 if (FirstNoEscape != IsNoEscape)
12377 CanUseFirst = false;
12378 if (SecondNoEscape != IsNoEscape)
12379 CanUseSecond = false;
12380 }
12381
12382 if (!NeedParamInfo)
12383 NewParamInfos.clear();
12384
12385 return true;
12386}
12387
12389 if (auto It = ObjCLayouts.find(D); It != ObjCLayouts.end()) {
12390 It->second = nullptr;
12391 for (auto *SubClass : ObjCSubClasses.lookup(D))
12392 ResetObjCLayout(SubClass);
12393 }
12394}
12395
12396/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
12397/// 'RHS' attributes and returns the merged version; including for function
12398/// return types.
12400 QualType LHSCan = getCanonicalType(LHS),
12401 RHSCan = getCanonicalType(RHS);
12402 // If two types are identical, they are compatible.
12403 if (LHSCan == RHSCan)
12404 return LHS;
12405 if (RHSCan->isFunctionType()) {
12406 if (!LHSCan->isFunctionType())
12407 return {};
12408 QualType OldReturnType =
12409 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
12410 QualType NewReturnType =
12411 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
12412 QualType ResReturnType =
12413 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
12414 if (ResReturnType.isNull())
12415 return {};
12416 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
12417 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
12418 // In either case, use OldReturnType to build the new function type.
12419 const auto *F = LHS->castAs<FunctionType>();
12420 if (const auto *FPT = cast<FunctionProtoType>(F)) {
12421 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12422 EPI.ExtInfo = getFunctionExtInfo(LHS);
12423 QualType ResultType =
12424 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
12425 return ResultType;
12426 }
12427 }
12428 return {};
12429 }
12430
12431 // If the qualifiers are different, the types can still be merged.
12432 Qualifiers LQuals = LHSCan.getLocalQualifiers();
12433 Qualifiers RQuals = RHSCan.getLocalQualifiers();
12434
12435 if (LQuals.withoutObjCGCAttr() != RQuals.withoutObjCGCAttr()) {
12436 // Reject immediately, if anything but the GC qualifiers is different.
12437 return {};
12438 }
12439
12440 if (LQuals != RQuals) {
12441 // Exactly one GC qualifier difference is allowed: __strong is
12442 // okay if the other type has no GC qualifier but is an Objective
12443 // C object pointer (i.e. implicitly strong by default). We fix
12444 // this by pretending that the unqualified type was actually
12445 // qualified __strong.
12446 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
12447 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
12448 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
12449
12450 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
12451 return {};
12452
12453 if (GC_L == Qualifiers::Strong)
12454 return LHS;
12455 if (GC_R == Qualifiers::Strong)
12456 return RHS;
12457 return {};
12458 }
12459
12460 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
12461 QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType();
12462 QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType();
12463 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
12464 if (ResQT == LHSBaseQT)
12465 return LHS;
12466 if (ResQT == RHSBaseQT)
12467 return RHS;
12468 }
12469 return {};
12470}
12471
12472//===----------------------------------------------------------------------===//
12473// Integer Predicates
12474//===----------------------------------------------------------------------===//
12475
12477 if (const auto *ED = T->getAsEnumDecl())
12478 T = ED->getIntegerType();
12479 if (T->isBooleanType())
12480 return 1;
12481 if (const auto *EIT = T->getAs<BitIntType>())
12482 return EIT->getNumBits();
12483 // For builtin types, just use the standard type sizing method
12484 return (unsigned)getTypeSize(T);
12485}
12486
12488 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
12489 T->isFixedPointType()) &&
12490 "Unexpected type");
12491
12492 // Turn <4 x signed int> -> <4 x unsigned int>
12493 if (const auto *VTy = T->getAs<VectorType>())
12494 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
12495 VTy->getNumElements(), VTy->getVectorKind());
12496
12497 // For _BitInt, return an unsigned _BitInt with same width.
12498 if (const auto *EITy = T->getAs<BitIntType>())
12499 return getBitIntType(/*Unsigned=*/true, EITy->getNumBits());
12500
12501 // For the overflow behavior types, construct a new unsigned variant
12502 if (const auto *OBT = T->getAs<OverflowBehaviorType>())
12504 OBT->getBehaviorKind(),
12505 getCorrespondingUnsignedType(OBT->getUnderlyingType()));
12506
12507 // For enums, get the underlying integer type of the enum, and let the general
12508 // integer type signchanging code handle it.
12509 if (const auto *ED = T->getAsEnumDecl())
12510 T = ED->getIntegerType();
12511
12512 switch (T->castAs<BuiltinType>()->getKind()) {
12513 case BuiltinType::Char_U:
12514 // Plain `char` is mapped to `unsigned char` even if it's already unsigned
12515 case BuiltinType::Char_S:
12516 case BuiltinType::SChar:
12517 case BuiltinType::Char8:
12518 return UnsignedCharTy;
12519 case BuiltinType::Short:
12520 return UnsignedShortTy;
12521 case BuiltinType::Int:
12522 return UnsignedIntTy;
12523 case BuiltinType::Long:
12524 return UnsignedLongTy;
12525 case BuiltinType::LongLong:
12526 return UnsignedLongLongTy;
12527 case BuiltinType::Int128:
12528 return UnsignedInt128Ty;
12529 // wchar_t is special. It is either signed or not, but when it's signed,
12530 // there's no matching "unsigned wchar_t". Therefore we return the unsigned
12531 // version of its underlying type instead.
12532 case BuiltinType::WChar_S:
12533 return getUnsignedWCharType();
12534
12535 case BuiltinType::ShortAccum:
12536 return UnsignedShortAccumTy;
12537 case BuiltinType::Accum:
12538 return UnsignedAccumTy;
12539 case BuiltinType::LongAccum:
12540 return UnsignedLongAccumTy;
12541 case BuiltinType::SatShortAccum:
12543 case BuiltinType::SatAccum:
12544 return SatUnsignedAccumTy;
12545 case BuiltinType::SatLongAccum:
12547 case BuiltinType::ShortFract:
12548 return UnsignedShortFractTy;
12549 case BuiltinType::Fract:
12550 return UnsignedFractTy;
12551 case BuiltinType::LongFract:
12552 return UnsignedLongFractTy;
12553 case BuiltinType::SatShortFract:
12555 case BuiltinType::SatFract:
12556 return SatUnsignedFractTy;
12557 case BuiltinType::SatLongFract:
12559 default:
12560 assert((T->hasUnsignedIntegerRepresentation() ||
12561 T->isUnsignedFixedPointType()) &&
12562 "Unexpected signed integer or fixed point type");
12563 return T;
12564 }
12565}
12566
12568 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
12569 T->isFixedPointType()) &&
12570 "Unexpected type");
12571
12572 // Turn <4 x unsigned int> -> <4 x signed int>
12573 if (const auto *VTy = T->getAs<VectorType>())
12574 return getVectorType(getCorrespondingSignedType(VTy->getElementType()),
12575 VTy->getNumElements(), VTy->getVectorKind());
12576
12577 // For _BitInt, return a signed _BitInt with same width.
12578 if (const auto *EITy = T->getAs<BitIntType>())
12579 return getBitIntType(/*Unsigned=*/false, EITy->getNumBits());
12580
12581 // For enums, get the underlying integer type of the enum, and let the general
12582 // integer type signchanging code handle it.
12583 if (const auto *ED = T->getAsEnumDecl())
12584 T = ED->getIntegerType();
12585
12586 switch (T->castAs<BuiltinType>()->getKind()) {
12587 case BuiltinType::Char_S:
12588 // Plain `char` is mapped to `signed char` even if it's already signed
12589 case BuiltinType::Char_U:
12590 case BuiltinType::UChar:
12591 case BuiltinType::Char8:
12592 return SignedCharTy;
12593 case BuiltinType::UShort:
12594 return ShortTy;
12595 case BuiltinType::UInt:
12596 return IntTy;
12597 case BuiltinType::ULong:
12598 return LongTy;
12599 case BuiltinType::ULongLong:
12600 return LongLongTy;
12601 case BuiltinType::UInt128:
12602 return Int128Ty;
12603 // wchar_t is special. It is either unsigned or not, but when it's unsigned,
12604 // there's no matching "signed wchar_t". Therefore we return the signed
12605 // version of its underlying type instead.
12606 case BuiltinType::WChar_U:
12607 return getSignedWCharType();
12608
12609 case BuiltinType::UShortAccum:
12610 return ShortAccumTy;
12611 case BuiltinType::UAccum:
12612 return AccumTy;
12613 case BuiltinType::ULongAccum:
12614 return LongAccumTy;
12615 case BuiltinType::SatUShortAccum:
12616 return SatShortAccumTy;
12617 case BuiltinType::SatUAccum:
12618 return SatAccumTy;
12619 case BuiltinType::SatULongAccum:
12620 return SatLongAccumTy;
12621 case BuiltinType::UShortFract:
12622 return ShortFractTy;
12623 case BuiltinType::UFract:
12624 return FractTy;
12625 case BuiltinType::ULongFract:
12626 return LongFractTy;
12627 case BuiltinType::SatUShortFract:
12628 return SatShortFractTy;
12629 case BuiltinType::SatUFract:
12630 return SatFractTy;
12631 case BuiltinType::SatULongFract:
12632 return SatLongFractTy;
12633 default:
12634 assert(
12635 (T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) &&
12636 "Unexpected signed integer or fixed point type");
12637 return T;
12638 }
12639}
12640
12642
12645
12646//===----------------------------------------------------------------------===//
12647// Builtin Type Computation
12648//===----------------------------------------------------------------------===//
12649
12650/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
12651/// pointer over the consumed characters. This returns the resultant type. If
12652/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
12653/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
12654/// a vector of "i*".
12655///
12656/// RequiresICE is filled in on return to indicate whether the value is required
12657/// to be an Integer Constant Expression.
12658static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
12660 bool &RequiresICE,
12661 bool AllowTypeModifiers) {
12662 // Modifiers.
12663 int HowLong = 0;
12664 bool Signed = false, Unsigned = false;
12665 bool IsChar = false, IsShort = false;
12666 RequiresICE = false;
12667
12668 // Read the prefixed modifiers first.
12669 bool Done = false;
12670 #ifndef NDEBUG
12671 bool IsSpecial = false;
12672 #endif
12673 while (!Done) {
12674 switch (*Str++) {
12675 default: Done = true; --Str; break;
12676 case 'I':
12677 RequiresICE = true;
12678 break;
12679 case 'S':
12680 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
12681 assert(!Signed && "Can't use 'S' modifier multiple times!");
12682 Signed = true;
12683 break;
12684 case 'U':
12685 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
12686 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
12687 Unsigned = true;
12688 break;
12689 case 'B':
12690 // This modifier represents int8 type (byte-width).
12691 assert(!IsSpecial &&
12692 "Can't use two 'N', 'W', 'Z', 'O', 'B', or 'T' modifiers!");
12693 assert(HowLong == 0 && "Can't use both 'L' and 'B' modifiers!");
12694#ifndef NDEBUG
12695 IsSpecial = true;
12696#endif
12697 IsChar = true;
12698 break;
12699 case 'T':
12700 // This modifier represents int16 type (short-width).
12701 assert(!IsSpecial &&
12702 "Can't use two 'N', 'W', 'Z', 'O', 'B', or 'T' modifiers!");
12703 assert(HowLong == 0 && "Can't use both 'L' and 'T' modifiers!");
12704#ifndef NDEBUG
12705 IsSpecial = true;
12706#endif
12707 IsShort = true;
12708 break;
12709 case 'L':
12710 assert(!IsSpecial &&
12711 "Can't use 'L' with 'W', 'N', 'Z', 'O', 'B', or 'T' modifiers");
12712 assert(HowLong <= 2 && "Can't have LLLL modifier");
12713 ++HowLong;
12714 break;
12715 case 'N':
12716 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
12717 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12718 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
12719 #ifndef NDEBUG
12720 IsSpecial = true;
12721 #endif
12722 if (Context.getTargetInfo().getLongWidth() == 32)
12723 ++HowLong;
12724 break;
12725 case 'W':
12726 // This modifier represents int64 type.
12727 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12728 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
12729 #ifndef NDEBUG
12730 IsSpecial = true;
12731 #endif
12732 switch (Context.getTargetInfo().getInt64Type()) {
12733 default:
12734 llvm_unreachable("Unexpected integer type");
12736 HowLong = 1;
12737 break;
12739 HowLong = 2;
12740 break;
12741 }
12742 break;
12743 case 'Z':
12744 // This modifier represents int32 type.
12745 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12746 assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
12747 #ifndef NDEBUG
12748 IsSpecial = true;
12749 #endif
12750 switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) {
12751 default:
12752 llvm_unreachable("Unexpected integer type");
12754 HowLong = 0;
12755 break;
12757 HowLong = 1;
12758 break;
12760 HowLong = 2;
12761 break;
12762 }
12763 break;
12764 case 'O':
12765 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12766 assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
12767 #ifndef NDEBUG
12768 IsSpecial = true;
12769 #endif
12770 if (Context.getLangOpts().OpenCL)
12771 HowLong = 1;
12772 else
12773 HowLong = 2;
12774 break;
12775 }
12776 }
12777
12778 QualType Type;
12779
12780 // Read the base type.
12781 switch (*Str++) {
12782 default:
12783 llvm_unreachable("Unknown builtin type letter!");
12784 case 'x':
12785 assert(HowLong == 0 && !Signed && !Unsigned &&
12786 "Bad modifiers used with 'x'!");
12787 Type = Context.Float16Ty;
12788 break;
12789 case 'y':
12790 assert(HowLong == 0 && !Signed && !Unsigned &&
12791 "Bad modifiers used with 'y'!");
12792 Type = Context.BFloat16Ty;
12793 break;
12794 case 'v':
12795 assert(HowLong == 0 && !Signed && !Unsigned &&
12796 "Bad modifiers used with 'v'!");
12797 Type = Context.VoidTy;
12798 break;
12799 case 'h':
12800 assert(HowLong == 0 && !Signed && !Unsigned &&
12801 "Bad modifiers used with 'h'!");
12802 Type = Context.HalfTy;
12803 break;
12804 case 'f':
12805 assert(HowLong == 0 && !Signed && !Unsigned &&
12806 "Bad modifiers used with 'f'!");
12807 Type = Context.FloatTy;
12808 break;
12809 case 'd':
12810 assert(HowLong < 3 && !Signed && !Unsigned &&
12811 "Bad modifiers used with 'd'!");
12812 if (HowLong == 1)
12813 Type = Context.LongDoubleTy;
12814 else if (HowLong == 2)
12815 Type = Context.Float128Ty;
12816 else
12817 Type = Context.DoubleTy;
12818 break;
12819 case 's':
12820 assert(HowLong == 0 && "Bad modifiers used with 's'!");
12821 if (Unsigned)
12822 Type = Context.UnsignedShortTy;
12823 else
12824 Type = Context.ShortTy;
12825 break;
12826 case 'i':
12827 if (IsChar)
12828 Type = Unsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
12829 else if (IsShort)
12830 Type = Unsigned ? Context.UnsignedShortTy : Context.ShortTy;
12831 else if (HowLong == 3)
12832 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
12833 else if (HowLong == 2)
12834 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
12835 else if (HowLong == 1)
12836 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
12837 else
12838 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
12839 break;
12840 case 'c':
12841 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
12842 if (Signed)
12843 Type = Context.SignedCharTy;
12844 else if (Unsigned)
12845 Type = Context.UnsignedCharTy;
12846 else
12847 Type = Context.CharTy;
12848 break;
12849 case 'b': // boolean
12850 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
12851 Type = Context.BoolTy;
12852 break;
12853 case 'z': // size_t.
12854 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
12855 Type = Context.getSizeType();
12856 break;
12857 case 'w': // wchar_t.
12858 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
12859 Type = Context.getWideCharType();
12860 break;
12861 case 'F':
12862 Type = Context.getCFConstantStringType();
12863 break;
12864 case 'G':
12865 Type = Context.getObjCIdType();
12866 break;
12867 case 'H':
12868 Type = Context.getObjCSelType();
12869 break;
12870 case 'M':
12871 Type = Context.getObjCSuperType();
12872 break;
12873 case 'a':
12874 Type = Context.getBuiltinVaListType();
12875 assert(!Type.isNull() && "builtin va list type not initialized!");
12876 break;
12877 case 'A':
12878 // This is a "reference" to a va_list; however, what exactly
12879 // this means depends on how va_list is defined. There are two
12880 // different kinds of va_list: ones passed by value, and ones
12881 // passed by reference. An example of a by-value va_list is
12882 // x86, where va_list is a char*. An example of by-ref va_list
12883 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
12884 // we want this argument to be a char*&; for x86-64, we want
12885 // it to be a __va_list_tag*.
12886 Type = Context.getBuiltinVaListType();
12887 assert(!Type.isNull() && "builtin va list type not initialized!");
12888 if (Type->isArrayType())
12889 Type = Context.getArrayDecayedType(Type);
12890 else
12891 Type = Context.getLValueReferenceType(Type);
12892 break;
12893 case 'q': {
12894 char *End;
12895 unsigned NumElements = strtoul(Str, &End, 10);
12896 assert(End != Str && "Missing vector size");
12897 Str = End;
12898
12899 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12900 RequiresICE, false);
12901 assert(!RequiresICE && "Can't require vector ICE");
12902
12903 Type = Context.getScalableVectorType(ElementType, NumElements);
12904 break;
12905 }
12906 case 'Q': {
12907 switch (*Str++) {
12908 case 'a': {
12909 Type = Context.SveCountTy;
12910 break;
12911 }
12912 case 'b': {
12913 Type = Context.AMDGPUBufferRsrcTy;
12914 break;
12915 }
12916 case 'c': {
12917 Type = Context.AMDGPUFeaturePredicateTy;
12918 break;
12919 }
12920 case 't': {
12921 Type = Context.AMDGPUTextureTy;
12922 break;
12923 }
12924 case 'r': {
12925 Type = Context.HLSLResourceTy;
12926 break;
12927 }
12928 default:
12929 llvm_unreachable("Unexpected target builtin type");
12930 }
12931 break;
12932 }
12933 case 'V': {
12934 char *End;
12935 unsigned NumElements = strtoul(Str, &End, 10);
12936 assert(End != Str && "Missing vector size");
12937 Str = End;
12938
12939 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12940 RequiresICE, false);
12941 assert(!RequiresICE && "Can't require vector ICE");
12942
12943 // TODO: No way to make AltiVec vectors in builtins yet.
12944 Type = Context.getVectorType(ElementType, NumElements, VectorKind::Generic);
12945 break;
12946 }
12947 case 'E': {
12948 char *End;
12949
12950 unsigned NumElements = strtoul(Str, &End, 10);
12951 assert(End != Str && "Missing vector size");
12952
12953 Str = End;
12954
12955 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12956 false);
12957 Type = Context.getExtVectorType(ElementType, NumElements);
12958 break;
12959 }
12960 case 'X': {
12961 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12962 false);
12963 assert(!RequiresICE && "Can't require complex ICE");
12964 Type = Context.getComplexType(ElementType);
12965 break;
12966 }
12967 case 'Y':
12968 Type = Context.getPointerDiffType();
12969 break;
12970 case 'P':
12971 Type = Context.getFILEType();
12972 if (Type.isNull()) {
12974 return {};
12975 }
12976 break;
12977 case 'J':
12978 if (Signed)
12979 Type = Context.getsigjmp_bufType();
12980 else
12981 Type = Context.getjmp_bufType();
12982
12983 if (Type.isNull()) {
12985 return {};
12986 }
12987 break;
12988 case 'K':
12989 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
12990 Type = Context.getucontext_tType();
12991
12992 if (Type.isNull()) {
12994 return {};
12995 }
12996 break;
12997 case 'p':
12998 Type = Context.getProcessIDType();
12999 break;
13000 case 'm':
13001 Type = Context.MFloat8Ty;
13002 break;
13003 }
13004
13005 // If there are modifiers and if we're allowed to parse them, go for it.
13006 Done = !AllowTypeModifiers;
13007 while (!Done) {
13008 switch (char c = *Str++) {
13009 default: Done = true; --Str; break;
13010 case '*':
13011 case '&': {
13012 // Both pointers and references can have their pointee types
13013 // qualified with an address space.
13014 char *End;
13015 unsigned AddrSpace = strtoul(Str, &End, 10);
13016 if (End != Str) {
13017 // Note AddrSpace == 0 is not the same as an unspecified address space.
13018 Type = Context.getAddrSpaceQualType(
13019 Type,
13020 Context.getLangASForBuiltinAddressSpace(AddrSpace));
13021 Str = End;
13022 }
13023 if (c == '*')
13024 Type = Context.getPointerType(Type);
13025 else
13026 Type = Context.getLValueReferenceType(Type);
13027 break;
13028 }
13029 // FIXME: There's no way to have a built-in with an rvalue ref arg.
13030 case 'C':
13031 Type = Type.withConst();
13032 break;
13033 case 'D':
13034 Type = Context.getVolatileType(Type);
13035 break;
13036 case 'R':
13037 Type = Type.withRestrict();
13038 break;
13039 }
13040 }
13041
13042 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
13043 "Integer constant 'I' type must be an integer");
13044
13045 return Type;
13046}
13047
13048// On some targets such as PowerPC, some of the builtins are defined with custom
13049// type descriptors for target-dependent types. These descriptors are decoded in
13050// other functions, but it may be useful to be able to fall back to default
13051// descriptor decoding to define builtins mixing target-dependent and target-
13052// independent types. This function allows decoding one type descriptor with
13053// default decoding.
13054QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context,
13055 GetBuiltinTypeError &Error, bool &RequireICE,
13056 bool AllowTypeModifiers) const {
13057 return DecodeTypeFromStr(Str, Context, Error, RequireICE, AllowTypeModifiers);
13058}
13059
13060/// GetBuiltinType - Return the type for the specified builtin.
13063 unsigned *IntegerConstantArgs) const {
13064 const char *TypeStr = BuiltinInfo.getTypeString(Id);
13065 if (TypeStr[0] == '\0') {
13067 return {};
13068 }
13069
13070 SmallVector<QualType, 8> ArgTypes;
13071
13072 bool RequiresICE = false;
13073 Error = GE_None;
13074 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
13075 RequiresICE, true);
13076 if (Error != GE_None)
13077 return {};
13078
13079 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
13080
13081 while (TypeStr[0] && TypeStr[0] != '.') {
13082 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
13083 if (Error != GE_None)
13084 return {};
13085
13086 // If this argument is required to be an IntegerConstantExpression and the
13087 // caller cares, fill in the bitmask we return.
13088 if (RequiresICE && IntegerConstantArgs)
13089 *IntegerConstantArgs |= 1 << ArgTypes.size();
13090
13091 // Do array -> pointer decay. The builtin should use the decayed type.
13092 if (Ty->isArrayType())
13093 Ty = getArrayDecayedType(Ty);
13094
13095 ArgTypes.push_back(Ty);
13096 }
13097
13098 if (Id == Builtin::BI__GetExceptionInfo)
13099 return {};
13100
13101 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
13102 "'.' should only occur at end of builtin type list!");
13103
13104 bool Variadic = (TypeStr[0] == '.');
13105
13106 FunctionType::ExtInfo EI(Target->getDefaultCallingConv());
13107 if (BuiltinInfo.isNoReturn(Id))
13108 EI = EI.withNoReturn(true);
13109
13110 // We really shouldn't be making a no-proto type here.
13111 if (ArgTypes.empty() && Variadic && !getLangOpts().requiresStrictPrototypes())
13112 return getFunctionNoProtoType(ResType, EI);
13113
13115 EPI.ExtInfo = EI;
13116 EPI.Variadic = Variadic;
13117 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
13118 EPI.ExceptionSpec.Type =
13120
13121 return getFunctionType(ResType, ArgTypes, EPI);
13122}
13123
13125 const FunctionDecl *FD) {
13126 if (!FD->isExternallyVisible())
13127 return GVA_Internal;
13128
13129 // Non-user-provided functions get emitted as weak definitions with every
13130 // use, no matter whether they've been explicitly instantiated etc.
13131 if (!FD->isUserProvided())
13132 return GVA_DiscardableODR;
13133
13135 switch (FD->getTemplateSpecializationKind()) {
13136 case TSK_Undeclared:
13139 break;
13140
13142 return GVA_StrongODR;
13143
13144 // C++11 [temp.explicit]p10:
13145 // [ Note: The intent is that an inline function that is the subject of
13146 // an explicit instantiation declaration will still be implicitly
13147 // instantiated when used so that the body can be considered for
13148 // inlining, but that no out-of-line copy of the inline function would be
13149 // generated in the translation unit. -- end note ]
13152
13155 break;
13156 }
13157
13158 if (!FD->isInlined())
13159 return External;
13160
13161 if ((!Context.getLangOpts().CPlusPlus &&
13162 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13163 !FD->hasAttr<DLLExportAttr>()) ||
13164 FD->hasAttr<GNUInlineAttr>()) {
13165 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
13166
13167 // GNU or C99 inline semantics. Determine whether this symbol should be
13168 // externally visible.
13169 if (auto *Def = FD->getDefinition();
13171 return External;
13172
13173 // C99 inline semantics, where the symbol is not externally visible.
13175 }
13176
13177 // Functions specified with extern and inline in -fms-compatibility mode
13178 // forcibly get emitted. While the body of the function cannot be later
13179 // replaced, the function definition cannot be discarded.
13180 if (FD->isMSExternInline())
13181 return GVA_StrongODR;
13182
13183 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13185 cast<CXXConstructorDecl>(FD)->isInheritingConstructor() &&
13186 !FD->hasAttr<DLLExportAttr>()) {
13187 // Both Clang and MSVC implement inherited constructors as forwarding
13188 // thunks that delegate to the base constructor. Keep non-dllexport
13189 // inheriting constructor thunks internal since they are not needed
13190 // outside the translation unit.
13191 //
13192 // dllexport inherited constructors are exempted so they are externally
13193 // visible, matching MSVC's export behavior. Inherited constructors
13194 // whose parameters prevent ABI-compatible forwarding (e.g. callee-
13195 // cleanup types) are excluded from export in Sema to avoid silent
13196 // runtime mismatches.
13197 return GVA_Internal;
13198 }
13199
13200 return GVA_DiscardableODR;
13201}
13202
13204 const Decl *D, GVALinkage L) {
13205 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
13206 // dllexport/dllimport on inline functions.
13207 if (D->hasAttr<DLLImportAttr>()) {
13208 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
13210 } else if (D->hasAttr<DLLExportAttr>()) {
13211 if (L == GVA_DiscardableODR)
13212 return GVA_StrongODR;
13213 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) {
13214 // Device-side functions with __global__ attribute must always be
13215 // visible externally so they can be launched from host.
13216 if (D->hasAttr<CUDAGlobalAttr>() &&
13217 (L == GVA_DiscardableODR || L == GVA_Internal))
13218 return GVA_StrongODR;
13219 // Single source offloading languages like CUDA/HIP need to be able to
13220 // access static device variables from host code of the same compilation
13221 // unit. This is done by externalizing the static variable with a shared
13222 // name between the host and device compilation which is the same for the
13223 // same compilation unit whereas different among different compilation
13224 // units.
13225 if (Context.shouldExternalize(D))
13226 return GVA_StrongExternal;
13227 }
13228 return L;
13229}
13230
13231/// Adjust the GVALinkage for a declaration based on what an external AST source
13232/// knows about whether there can be other definitions of this declaration.
13233static GVALinkage
13235 GVALinkage L) {
13236 ExternalASTSource *Source = Ctx.getExternalSource();
13237 if (!Source)
13238 return L;
13239
13240 switch (Source->hasExternalDefinitions(D)) {
13242 // Other translation units rely on us to provide the definition.
13243 if (L == GVA_DiscardableODR)
13244 return GVA_StrongODR;
13245 break;
13246
13249
13251 break;
13252 }
13253 return L;
13254}
13255
13261
13263 const VarDecl *VD) {
13264 // As an extension for interactive REPLs, make sure constant variables are
13265 // only emitted once instead of LinkageComputer::getLVForNamespaceScopeDecl
13266 // marking them as internal.
13267 if (Context.getLangOpts().CPlusPlus &&
13268 Context.getLangOpts().IncrementalExtensions &&
13269 VD->getType().isConstQualified() &&
13270 !VD->getType().isVolatileQualified() && !VD->isInline() &&
13272 return GVA_DiscardableODR;
13273
13274 if (!VD->isExternallyVisible())
13275 return GVA_Internal;
13276
13277 if (VD->isStaticLocal()) {
13278 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
13279 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
13280 LexicalContext = LexicalContext->getLexicalParent();
13281
13282 // ObjC Blocks can create local variables that don't have a FunctionDecl
13283 // LexicalContext.
13284 if (!LexicalContext)
13285 return GVA_DiscardableODR;
13286
13287 // Otherwise, let the static local variable inherit its linkage from the
13288 // nearest enclosing function.
13289 auto StaticLocalLinkage =
13290 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
13291
13292 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
13293 // be emitted in any object with references to the symbol for the object it
13294 // contains, whether inline or out-of-line."
13295 // Similar behavior is observed with MSVC. An alternative ABI could use
13296 // StrongODR/AvailableExternally to match the function, but none are
13297 // known/supported currently.
13298 if (StaticLocalLinkage == GVA_StrongODR ||
13299 StaticLocalLinkage == GVA_AvailableExternally)
13300 return GVA_DiscardableODR;
13301 return StaticLocalLinkage;
13302 }
13303
13304 // MSVC treats in-class initialized static data members as definitions.
13305 // By giving them non-strong linkage, out-of-line definitions won't
13306 // cause link errors.
13307 if (Context.isMSStaticDataMemberInlineDefinition(VD))
13308 return GVA_DiscardableODR;
13309
13310 // Most non-template variables have strong linkage; inline variables are
13311 // linkonce_odr or (occasionally, for compatibility) weak_odr.
13312 GVALinkage StrongLinkage;
13313 switch (Context.getInlineVariableDefinitionKind(VD)) {
13315 StrongLinkage = GVA_StrongExternal;
13316 break;
13319 StrongLinkage = GVA_DiscardableODR;
13320 break;
13322 StrongLinkage = GVA_StrongODR;
13323 break;
13324 }
13325
13326 switch (VD->getTemplateSpecializationKind()) {
13327 case TSK_Undeclared:
13328 return StrongLinkage;
13329
13331 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13332 VD->isStaticDataMember()
13334 : StrongLinkage;
13335
13337 return GVA_StrongODR;
13338
13341
13343 return GVA_DiscardableODR;
13344 }
13345
13346 llvm_unreachable("Invalid Linkage!");
13347}
13348
13354
13356 if (const auto *VD = dyn_cast<VarDecl>(D)) {
13357 if (!VD->isFileVarDecl())
13358 return false;
13359 // Global named register variables (GNU extension) are never emitted.
13360 if (VD->getStorageClass() == SC_Register)
13361 return false;
13362 if (VD->getDescribedVarTemplate() ||
13364 return false;
13365 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
13366 // We never need to emit an uninstantiated function template.
13367 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
13368 return false;
13369 } else if (isa<PragmaCommentDecl>(D))
13370 return true;
13372 return true;
13373 else if (isa<OMPRequiresDecl>(D))
13374 return true;
13375 else if (isa<OMPThreadPrivateDecl>(D))
13376 return !D->getDeclContext()->isDependentContext();
13377 else if (isa<OMPAllocateDecl>(D))
13378 return !D->getDeclContext()->isDependentContext();
13380 return !D->getDeclContext()->isDependentContext();
13381 else if (isa<ImportDecl>(D))
13382 return true;
13383 else
13384 return false;
13385
13386 // If this is a member of a class template, we do not need to emit it.
13388 return false;
13389
13390 // Weak references don't produce any output by themselves.
13391 if (D->hasAttr<WeakRefAttr>())
13392 return false;
13393
13394 // SYCL device compilation requires that functions defined with the
13395 // sycl_kernel_entry_point or sycl_external attributes be emitted. All
13396 // other entities are emitted only if they are used by a function
13397 // defined with one of those attributes.
13398 if (LangOpts.SYCLIsDevice)
13399 return isa<FunctionDecl>(D) && (D->hasAttr<SYCLKernelEntryPointAttr>() ||
13400 D->hasAttr<SYCLExternalAttr>());
13401
13402 // Aliases and used decls are required.
13403 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
13404 return true;
13405
13406 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
13407 // Forward declarations aren't required.
13408 if (!FD->doesThisDeclarationHaveABody())
13409 return FD->doesDeclarationForceExternallyVisibleDefinition();
13410
13411 // Constructors and destructors are required.
13412 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
13413 return true;
13414
13415 // The key function for a class is required. This rule only comes
13416 // into play when inline functions can be key functions, though.
13417 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
13418 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
13419 const CXXRecordDecl *RD = MD->getParent();
13420 if (MD->isOutOfLine() && RD->isDynamicClass()) {
13421 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
13422 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
13423 return true;
13424 }
13425 }
13426 }
13427
13429
13430 // static, static inline, always_inline, and extern inline functions can
13431 // always be deferred. Normal inline functions can be deferred in C99/C++.
13432 // Implicit template instantiations can also be deferred in C++.
13434 }
13435
13436 const auto *VD = cast<VarDecl>(D);
13437 assert(VD->isFileVarDecl() && "Expected file scoped var");
13438
13439 // If the decl is marked as `declare target to`, it should be emitted for the
13440 // host and for the device.
13441 if (LangOpts.OpenMP &&
13442 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
13443 return true;
13444
13445 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
13447 return false;
13448
13449 if (VD->shouldEmitInExternalSource())
13450 return false;
13451
13452 // Variables that can be needed in other TUs are required.
13455 return true;
13456
13457 // We never need to emit a variable that is available in another TU.
13459 return false;
13460
13461 // Variables that have destruction with side-effects are required.
13462 if (VD->needsDestruction(*this))
13463 return true;
13464
13465 // Variables that have initialization with side-effects are required.
13466 if (VD->hasInitWithSideEffects())
13467 return true;
13468
13469 // Likewise, variables with tuple-like bindings are required if their
13470 // bindings have side-effects.
13471 if (const auto *DD = dyn_cast<DecompositionDecl>(VD)) {
13472 for (const auto *BD : DD->flat_bindings())
13473 if (const auto *BindingVD = BD->getHoldingVar())
13474 if (DeclMustBeEmitted(BindingVD))
13475 return true;
13476 }
13477
13478 return false;
13479}
13480
13482 const FunctionDecl *FD,
13483 llvm::function_ref<void(FunctionDecl *)> Pred) const {
13484 assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
13485 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
13486 FD = FD->getMostRecentDecl();
13487 // FIXME: The order of traversal here matters and depends on the order of
13488 // lookup results, which happens to be (mostly) oldest-to-newest, but we
13489 // shouldn't rely on that.
13490 for (auto *CurDecl :
13492 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
13493 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
13494 SeenDecls.insert(CurFD).second) {
13495 Pred(CurFD);
13496 }
13497 }
13498}
13499
13501 bool IsCXXMethod) const {
13502 // Pass through to the C++ ABI object
13503 if (IsCXXMethod)
13504 return ABI->getDefaultMethodCallConv(IsVariadic);
13505
13506 switch (LangOpts.getDefaultCallingConv()) {
13508 break;
13510 return CC_C;
13512 if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
13513 return CC_X86FastCall;
13514 break;
13516 if (!IsVariadic)
13517 return CC_X86StdCall;
13518 break;
13520 // __vectorcall cannot be applied to variadic functions.
13521 if (!IsVariadic)
13522 return CC_X86VectorCall;
13523 break;
13525 // __regcall cannot be applied to variadic functions.
13526 if (!IsVariadic)
13527 return CC_X86RegCall;
13528 break;
13530 if (!IsVariadic)
13531 return CC_M68kRTD;
13532 break;
13533 }
13534 return Target->getDefaultCallingConv();
13535}
13536
13538 // Pass through to the C++ ABI object
13539 return ABI->isNearlyEmpty(RD);
13540}
13541
13543 if (!VTContext) {
13544 auto ABI = Target->getCXXABI();
13545 if (ABI.isMicrosoft())
13546 VTContext.reset(new MicrosoftVTableContext(*this));
13547 else {
13548 VTContext.reset(new ItaniumVTableContext(*this));
13549 }
13550 }
13551 return VTContext.get();
13552}
13553
13555 if (!T)
13556 T = Target;
13557 switch (T->getCXXABI().getKind()) {
13558 case TargetCXXABI::AppleARM64:
13559 case TargetCXXABI::Fuchsia:
13560 case TargetCXXABI::GenericAArch64:
13561 case TargetCXXABI::GenericItanium:
13562 case TargetCXXABI::GenericARM:
13563 case TargetCXXABI::GenericMIPS:
13564 case TargetCXXABI::iOS:
13565 case TargetCXXABI::WebAssembly:
13566 case TargetCXXABI::WatchOS:
13567 case TargetCXXABI::XL:
13569 case TargetCXXABI::Microsoft:
13571 }
13572 llvm_unreachable("Unsupported ABI");
13573}
13574
13576 assert(T.getCXXABI().getKind() != TargetCXXABI::Microsoft &&
13577 "Device mangle context does not support Microsoft mangling.");
13578 switch (T.getCXXABI().getKind()) {
13579 case TargetCXXABI::AppleARM64:
13580 case TargetCXXABI::Fuchsia:
13581 case TargetCXXABI::GenericAArch64:
13582 case TargetCXXABI::GenericItanium:
13583 case TargetCXXABI::GenericARM:
13584 case TargetCXXABI::GenericMIPS:
13585 case TargetCXXABI::iOS:
13586 case TargetCXXABI::WebAssembly:
13587 case TargetCXXABI::WatchOS:
13588 case TargetCXXABI::XL:
13590 *this, getDiagnostics(),
13591 [](ASTContext &, const NamedDecl *ND) -> UnsignedOrNone {
13592 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
13593 return RD->getDeviceLambdaManglingNumber();
13594 return std::nullopt;
13595 },
13596 /*IsAux=*/true);
13597 case TargetCXXABI::Microsoft:
13599 /*IsAux=*/true);
13600 }
13601 llvm_unreachable("Unsupported ABI");
13602}
13603
13605 // If the host and device have different C++ ABIs, mark it as the device
13606 // mangle context so that the mangling needs to retrieve the additional
13607 // device lambda mangling number instead of the regular host one.
13608 if (getAuxTargetInfo() && getTargetInfo().getCXXABI().isMicrosoft() &&
13609 getAuxTargetInfo()->getCXXABI().isItaniumFamily()) {
13611 }
13612
13614}
13615
13616CXXABI::~CXXABI() = default;
13617
13619 return ASTRecordLayouts.getMemorySize() +
13620 llvm::capacity_in_bytes(ObjCLayouts) +
13621 llvm::capacity_in_bytes(KeyFunctions) +
13622 llvm::capacity_in_bytes(ObjCImpls) +
13623 llvm::capacity_in_bytes(BlockVarCopyInits) +
13624 llvm::capacity_in_bytes(DeclAttrs) +
13625 llvm::capacity_in_bytes(TemplateOrInstantiation) +
13626 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
13627 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
13628 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
13629 llvm::capacity_in_bytes(OverriddenMethods) +
13630 llvm::capacity_in_bytes(Types) +
13631 llvm::capacity_in_bytes(VariableArrayTypes);
13632}
13633
13634/// getIntTypeForBitwidth -
13635/// sets integer QualTy according to specified details:
13636/// bitwidth, signed/unsigned.
13637/// Returns empty type if there is no appropriate target types.
13639 unsigned Signed) const {
13641 CanQualType QualTy = getFromTargetType(Ty);
13642 if (!QualTy && DestWidth == 128)
13643 return Signed ? Int128Ty : UnsignedInt128Ty;
13644 return QualTy;
13645}
13646
13648 unsigned Signed) const {
13649 return getFromTargetType(
13650 getTargetInfo().getLeastIntTypeByWidth(DestWidth, Signed));
13651}
13652
13653/// getRealTypeForBitwidth -
13654/// sets floating point QualTy according to specified bitwidth.
13655/// Returns empty type if there is no appropriate target types.
13657 FloatModeKind ExplicitType) const {
13658 FloatModeKind Ty =
13659 getTargetInfo().getRealTypeByWidth(DestWidth, ExplicitType);
13660 switch (Ty) {
13662 return HalfTy;
13664 return FloatTy;
13666 return DoubleTy;
13668 return LongDoubleTy;
13670 return Float128Ty;
13672 return Ibm128Ty;
13674 return {};
13675 }
13676
13677 llvm_unreachable("Unhandled TargetInfo::RealType value");
13678}
13679
13680void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
13681 if (Number <= 1)
13682 return;
13683
13684 MangleNumbers[ND] = Number;
13685
13686 if (Listener)
13687 Listener->AddedManglingNumber(ND, Number);
13688}
13689
13691 bool ForAuxTarget) const {
13692 auto I = MangleNumbers.find(ND);
13693 unsigned Res = I != MangleNumbers.end() ? I->second : 1;
13694 // CUDA/HIP host compilation encodes host and device mangling numbers
13695 // as lower and upper half of 32 bit integer.
13696 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice) {
13697 Res = ForAuxTarget ? Res >> 16 : Res & 0xFFFF;
13698 } else {
13699 assert(!ForAuxTarget && "Only CUDA/HIP host compilation supports mangling "
13700 "number for aux target");
13701 }
13702 return Res > 1 ? Res : 1;
13703}
13704
13705void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
13706 if (Number <= 1)
13707 return;
13708
13709 StaticLocalNumbers[VD] = Number;
13710
13711 if (Listener)
13712 Listener->AddedStaticLocalNumbers(VD, Number);
13713}
13714
13716 auto I = StaticLocalNumbers.find(VD);
13717 return I != StaticLocalNumbers.end() ? I->second : 1;
13718}
13719
13721 bool IsDestroying) {
13722 if (!IsDestroying) {
13723 assert(!DestroyingOperatorDeletes.contains(FD->getCanonicalDecl()));
13724 return;
13725 }
13726 DestroyingOperatorDeletes.insert(FD->getCanonicalDecl());
13727}
13728
13730 return DestroyingOperatorDeletes.contains(FD->getCanonicalDecl());
13731}
13732
13734 bool IsTypeAware) {
13735 if (!IsTypeAware) {
13736 assert(!TypeAwareOperatorNewAndDeletes.contains(FD->getCanonicalDecl()));
13737 return;
13738 }
13739 TypeAwareOperatorNewAndDeletes.insert(FD->getCanonicalDecl());
13740}
13741
13743 return TypeAwareOperatorNewAndDeletes.contains(FD->getCanonicalDecl());
13744}
13745
13747 FunctionDecl *OperatorDelete,
13748 OperatorDeleteKind K) const {
13749 switch (K) {
13751 OperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] = OperatorDelete;
13752 break;
13754 GlobalOperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] =
13755 OperatorDelete;
13756 break;
13758 ArrayOperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] =
13759 OperatorDelete;
13760 break;
13762 GlobalArrayOperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] =
13763 OperatorDelete;
13764 break;
13765 }
13766}
13767
13769 OperatorDeleteKind K) const {
13770 switch (K) {
13772 return OperatorDeletesForVirtualDtor.contains(Dtor->getCanonicalDecl());
13774 return GlobalOperatorDeletesForVirtualDtor.contains(
13775 Dtor->getCanonicalDecl());
13777 return ArrayOperatorDeletesForVirtualDtor.contains(
13778 Dtor->getCanonicalDecl());
13780 return GlobalArrayOperatorDeletesForVirtualDtor.contains(
13781 Dtor->getCanonicalDecl());
13782 }
13783 return false;
13784}
13785
13788 OperatorDeleteKind K) const {
13789 const CXXDestructorDecl *Canon = Dtor->getCanonicalDecl();
13790 switch (K) {
13792 if (OperatorDeletesForVirtualDtor.contains(Canon))
13793 return OperatorDeletesForVirtualDtor[Canon];
13794 return nullptr;
13796 if (GlobalOperatorDeletesForVirtualDtor.contains(Canon))
13797 return GlobalOperatorDeletesForVirtualDtor[Canon];
13798 return nullptr;
13800 if (ArrayOperatorDeletesForVirtualDtor.contains(Canon))
13801 return ArrayOperatorDeletesForVirtualDtor[Canon];
13802 return nullptr;
13804 if (GlobalArrayOperatorDeletesForVirtualDtor.contains(Canon))
13805 return GlobalArrayOperatorDeletesForVirtualDtor[Canon];
13806 return nullptr;
13807 }
13808 return nullptr;
13809}
13810
13812 const CXXRecordDecl *RD) {
13813 if (!getTargetInfo().emitVectorDeletingDtors(getLangOpts()))
13814 return false;
13815
13816 return MaybeRequireVectorDeletingDtor.count(RD);
13817}
13818
13820 const CXXRecordDecl *RD) {
13821 if (!getTargetInfo().emitVectorDeletingDtors(getLangOpts()))
13822 return;
13823
13824 MaybeRequireVectorDeletingDtor.insert(RD);
13825}
13826
13829 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13830 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
13831 if (!MCtx)
13833 return *MCtx;
13834}
13835
13838 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13839 std::unique_ptr<MangleNumberingContext> &MCtx =
13840 ExtraMangleNumberingContexts[D];
13841 if (!MCtx)
13843 return *MCtx;
13844}
13845
13846std::unique_ptr<MangleNumberingContext>
13848 return ABI->createMangleNumberingContext();
13849}
13850
13851const CXXConstructorDecl *
13853 return ABI->getCopyConstructorForExceptionObject(
13855}
13856
13858 CXXConstructorDecl *CD) {
13859 return ABI->addCopyConstructorForExceptionObject(
13862}
13863
13865 TypedefNameDecl *DD) {
13866 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
13867}
13868
13871 return ABI->getTypedefNameForUnnamedTagDecl(TD);
13872}
13873
13875 DeclaratorDecl *DD) {
13876 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
13877}
13878
13880 return ABI->getDeclaratorForUnnamedTagDecl(TD);
13881}
13882
13884 ParamIndices[D] = index;
13885}
13886
13888 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
13889 assert(I != ParamIndices.end() &&
13890 "ParmIndices lacks entry set by ParmVarDecl");
13891 return I->second;
13892}
13893
13895 unsigned Length) const {
13896 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
13897 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
13898 EltTy = EltTy.withConst();
13899
13900 EltTy = adjustStringLiteralBaseType(EltTy);
13901
13902 // Get an array type for the string, according to C99 6.4.5. This includes
13903 // the null terminator character.
13904 return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr,
13905 ArraySizeModifier::Normal, /*IndexTypeQuals*/ 0);
13906}
13907
13910 StringLiteral *&Result = StringLiteralCache[Key];
13911 if (!Result)
13913 *this, Key, StringLiteralKind::Ordinary,
13914 /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()),
13915 SourceLocation());
13916 return Result;
13917}
13918
13919MSGuidDecl *
13921 assert(MSGuidTagDecl && "building MS GUID without MS extensions?");
13922
13923 llvm::FoldingSetNodeID ID;
13924 MSGuidDecl::Profile(ID, Parts);
13925
13926 llvm::FoldingSetInsertToken Token;
13927 if (MSGuidDecl *Existing = MSGuidDecls.lookup(ID, Token))
13928 return Existing;
13929
13930 QualType GUIDType = getMSGuidType().withConst();
13931 MSGuidDecl *New = MSGuidDecl::Create(*this, GUIDType, Parts);
13932 MSGuidDecls.insert(New, Token);
13933 return New;
13934}
13935
13938 const APValue &APVal) const {
13939 llvm::FoldingSetNodeID ID;
13941
13942 llvm::FoldingSetInsertToken Token;
13943 if (UnnamedGlobalConstantDecl *Existing =
13944 UnnamedGlobalConstantDecls.lookup(ID, Token))
13945 return Existing;
13946
13948 UnnamedGlobalConstantDecl::Create(*this, Ty, APVal);
13949 UnnamedGlobalConstantDecls.insert(New, Token);
13950 return New;
13951}
13952
13955 assert(T->isRecordType() && "template param object of unexpected type");
13956
13957 // C++ [temp.param]p8:
13958 // [...] a static storage duration object of type 'const T' [...]
13959 T.addConst();
13960
13961 llvm::FoldingSetNodeID ID;
13963
13964 llvm::FoldingSetInsertToken Token;
13965 if (TemplateParamObjectDecl *Existing =
13966 TemplateParamObjectDecls.lookup(ID, Token))
13967 return Existing;
13968
13969 TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(*this, T, V);
13970 TemplateParamObjectDecls.insert(New, Token);
13971 return New;
13972}
13973
13975 const llvm::Triple &T = getTargetInfo().getTriple();
13976 if (!T.isOSDarwin())
13977 return false;
13978
13979 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
13980 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
13981 return false;
13982
13983 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
13984 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
13985 uint64_t Size = sizeChars.getQuantity();
13986 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
13987 unsigned Align = alignChars.getQuantity();
13988 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
13989 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
13990}
13991
13992bool
13994 const ObjCMethodDecl *MethodImpl) {
13995 // No point trying to match an unavailable/deprecated mothod.
13996 if (MethodDecl->hasAttr<UnavailableAttr>()
13997 || MethodDecl->hasAttr<DeprecatedAttr>())
13998 return false;
13999 if (MethodDecl->getObjCDeclQualifier() !=
14000 MethodImpl->getObjCDeclQualifier())
14001 return false;
14002 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
14003 return false;
14004
14005 if (MethodDecl->param_size() != MethodImpl->param_size())
14006 return false;
14007
14008 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
14009 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
14010 EF = MethodDecl->param_end();
14011 IM != EM && IF != EF; ++IM, ++IF) {
14012 const ParmVarDecl *DeclVar = (*IF);
14013 const ParmVarDecl *ImplVar = (*IM);
14014 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
14015 return false;
14016 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
14017 return false;
14018 }
14019
14020 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
14021}
14022
14024 LangAS AS;
14026 AS = LangAS::Default;
14027 else
14028 AS = QT->getPointeeType().getAddressSpace();
14029
14031}
14032
14035}
14036
14037bool ASTContext::hasSameExpr(const Expr *X, const Expr *Y) const {
14038 if (X == Y)
14039 return true;
14040 if (!X || !Y)
14041 return false;
14042 llvm::FoldingSetNodeID IDX, IDY;
14043 X->Profile(IDX, *this, /*Canonical=*/true);
14044 Y->Profile(IDY, *this, /*Canonical=*/true);
14045 return IDX == IDY;
14046}
14047
14048// The getCommon* helpers return, for given 'same' X and Y entities given as
14049// inputs, another entity which is also the 'same' as the inputs, but which
14050// is closer to the canonical form of the inputs, each according to a given
14051// criteria.
14052// The getCommon*Checked variants are 'null inputs not-allowed' equivalents of
14053// the regular ones.
14054
14056 if (!declaresSameEntity(X, Y))
14057 return nullptr;
14058 for (const Decl *DX : X->redecls()) {
14059 // If we reach Y before reaching the first decl, that means X is older.
14060 if (DX == Y)
14061 return X;
14062 // If we reach the first decl, then Y is older.
14063 if (DX->isFirstDecl())
14064 return Y;
14065 }
14066 llvm_unreachable("Corrupt redecls chain");
14067}
14068
14069template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
14070static T *getCommonDecl(T *X, T *Y) {
14071 return cast_or_null<T>(
14072 getCommonDecl(const_cast<Decl *>(cast_or_null<Decl>(X)),
14073 const_cast<Decl *>(cast_or_null<Decl>(Y))));
14074}
14075
14076template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
14077static T *getCommonDeclChecked(T *X, T *Y) {
14078 return cast<T>(getCommonDecl(const_cast<Decl *>(cast<Decl>(X)),
14079 const_cast<Decl *>(cast<Decl>(Y))));
14080}
14081
14083 TemplateName Y,
14084 bool IgnoreDeduced = false) {
14085 if (X.getAsVoidPointer() == Y.getAsVoidPointer())
14086 return X;
14087 // FIXME: There are cases here where we could find a common template name
14088 // with more sugar. For example one could be a SubstTemplateTemplate*
14089 // replacing the other.
14090 TemplateName CX = Ctx.getCanonicalTemplateName(X, IgnoreDeduced);
14091 if (CX.getAsVoidPointer() !=
14093 return TemplateName();
14094 return CX;
14095}
14096
14099 bool IgnoreDeduced) {
14100 TemplateName R = getCommonTemplateName(Ctx, X, Y, IgnoreDeduced);
14101 assert(R.getAsVoidPointer() != nullptr);
14102 return R;
14103}
14104
14106 ArrayRef<QualType> Ys, bool Unqualified = false) {
14107 assert(Xs.size() == Ys.size());
14108 SmallVector<QualType, 8> Rs(Xs.size());
14109 for (size_t I = 0; I < Rs.size(); ++I)
14110 Rs[I] = Ctx.getCommonSugaredType(Xs[I], Ys[I], Unqualified);
14111 return Rs;
14112}
14113
14114template <class T>
14115static SourceLocation getCommonAttrLoc(const T *X, const T *Y) {
14116 return X->getAttributeLoc() == Y->getAttributeLoc() ? X->getAttributeLoc()
14117 : SourceLocation();
14118}
14119
14121 const TemplateArgument &X,
14122 const TemplateArgument &Y) {
14123 if (X.getKind() != Y.getKind())
14124 return TemplateArgument();
14125
14126 switch (X.getKind()) {
14128 if (!Ctx.hasSameType(X.getAsType(), Y.getAsType()))
14129 return TemplateArgument();
14130 return TemplateArgument(
14131 Ctx.getCommonSugaredType(X.getAsType(), Y.getAsType()));
14133 if (!Ctx.hasSameType(X.getNullPtrType(), Y.getNullPtrType()))
14134 return TemplateArgument();
14135 return TemplateArgument(
14136 Ctx.getCommonSugaredType(X.getNullPtrType(), Y.getNullPtrType()),
14137 /*Unqualified=*/true);
14139 if (!Ctx.hasSameType(X.getAsExpr()->getType(), Y.getAsExpr()->getType()))
14140 return TemplateArgument();
14141 // FIXME: Try to keep the common sugar.
14142 return X;
14144 TemplateName TX = X.getAsTemplate(), TY = Y.getAsTemplate();
14145 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
14146 if (!CTN.getAsVoidPointer())
14147 return TemplateArgument();
14148 return TemplateArgument(CTN);
14149 }
14151 TemplateName TX = X.getAsTemplateOrTemplatePattern(),
14153 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
14154 if (!CTN.getAsVoidPointer())
14155 return TemplateName();
14156 auto NExpX = X.getNumTemplateExpansions();
14157 assert(NExpX == Y.getNumTemplateExpansions());
14158 return TemplateArgument(CTN, NExpX);
14159 }
14160 default:
14161 // FIXME: Handle the other argument kinds.
14162 return X;
14163 }
14164}
14165
14170 if (Xs.size() != Ys.size())
14171 return true;
14172 R.resize(Xs.size());
14173 for (size_t I = 0; I < R.size(); ++I) {
14174 R[I] = getCommonTemplateArgument(Ctx, Xs[I], Ys[I]);
14175 if (R[I].isNull())
14176 return true;
14177 }
14178 return false;
14179}
14180
14185 bool Different = getCommonTemplateArguments(Ctx, R, Xs, Ys);
14186 assert(!Different);
14187 (void)Different;
14188 return R;
14189}
14190
14191template <class T>
14193 bool IsSame) {
14194 ElaboratedTypeKeyword KX = X->getKeyword(), KY = Y->getKeyword();
14195 if (KX == KY)
14196 return KX;
14198 assert(!IsSame || KX == getCanonicalElaboratedTypeKeyword(KY));
14199 return KX;
14200}
14201
14202/// Returns a NestedNameSpecifier which has only the common sugar
14203/// present in both NNS1 and NNS2.
14206 NestedNameSpecifier NNS2, bool IsSame) {
14207 // If they are identical, all sugar is common.
14208 if (NNS1 == NNS2)
14209 return NNS1;
14210
14211 // IsSame implies both Qualifiers are equivalent.
14212 NestedNameSpecifier Canon = NNS1.getCanonical();
14213 if (Canon != NNS2.getCanonical()) {
14214 assert(!IsSame && "Should be the same NestedNameSpecifier");
14215 // If they are not the same, there is nothing to unify.
14216 return std::nullopt;
14217 }
14218
14219 NestedNameSpecifier R = std::nullopt;
14220 NestedNameSpecifier::Kind Kind = NNS1.getKind();
14221 assert(Kind == NNS2.getKind());
14222 switch (Kind) {
14224 auto [Namespace1, Prefix1] = NNS1.getAsNamespaceAndPrefix();
14225 auto [Namespace2, Prefix2] = NNS2.getAsNamespaceAndPrefix();
14226 auto Kind = Namespace1->getKind();
14227 if (Kind != Namespace2->getKind() ||
14228 (Kind == Decl::NamespaceAlias &&
14229 !declaresSameEntity(Namespace1, Namespace2))) {
14231 Ctx,
14232 ::getCommonDeclChecked(Namespace1->getNamespace(),
14233 Namespace2->getNamespace()),
14234 /*Prefix=*/std::nullopt);
14235 break;
14236 }
14237 // The prefixes for namespaces are not significant, its declaration
14238 // identifies it uniquely.
14239 NestedNameSpecifier Prefix = ::getCommonNNS(Ctx, Prefix1, Prefix2,
14240 /*IsSame=*/false);
14241 R = NestedNameSpecifier(Ctx, ::getCommonDeclChecked(Namespace1, Namespace2),
14242 Prefix);
14243 break;
14244 }
14246 const Type *T1 = NNS1.getAsType(), *T2 = NNS2.getAsType();
14247 const Type *T = Ctx.getCommonSugaredType(QualType(T1, 0), QualType(T2, 0),
14248 /*Unqualified=*/true)
14249 .getTypePtr();
14251 break;
14252 }
14254 // FIXME: Can __super even be used with data members?
14255 // If it's only usable in functions, we will never see it here,
14256 // unless we save the qualifiers used in function types.
14257 // In that case, it might be possible NNS2 is a type,
14258 // in which case we should degrade the result to
14259 // a CXXRecordType.
14261 NNS2.getAsMicrosoftSuper()));
14262 break;
14263 }
14266 // These are singletons.
14267 llvm_unreachable("singletons did not compare equal");
14268 }
14269 assert(R.getCanonical() == Canon);
14270 return R;
14271}
14272
14273template <class T>
14275 const T *Y, bool IsSame) {
14276 return ::getCommonNNS(Ctx, X->getQualifier(), Y->getQualifier(), IsSame);
14277}
14278
14279template <class T>
14280static QualType getCommonElementType(const ASTContext &Ctx, const T *X,
14281 const T *Y) {
14282 return Ctx.getCommonSugaredType(X->getElementType(), Y->getElementType());
14283}
14284
14286 QualType X, QualType Y,
14287 Qualifiers &QX,
14288 Qualifiers &QY) {
14289 QualType R = Ctx.getCommonSugaredType(X, Y,
14290 /*Unqualified=*/true);
14291 // Qualifiers common to both element types.
14292 Qualifiers RQ = R.getQualifiers();
14293 // For each side, move to the top level any qualifiers which are not common to
14294 // both element types. The caller must assume top level qualifiers might
14295 // be different, even if they are the same type, and can be treated as sugar.
14296 QX += X.getQualifiers() - RQ;
14297 QY += Y.getQualifiers() - RQ;
14298 return R;
14299}
14300
14301template <class T>
14303 Qualifiers &QX, const T *Y,
14304 Qualifiers &QY) {
14305 return getCommonTypeWithQualifierLifting(Ctx, X->getElementType(),
14306 Y->getElementType(), QX, QY);
14307}
14308
14309template <class T>
14310static QualType getCommonPointeeType(const ASTContext &Ctx, const T *X,
14311 const T *Y) {
14312 return Ctx.getCommonSugaredType(X->getPointeeType(), Y->getPointeeType());
14313}
14314
14315template <class T>
14316static auto *getCommonSizeExpr(const ASTContext &Ctx, T *X, T *Y) {
14317 assert(Ctx.hasSameExpr(X->getSizeExpr(), Y->getSizeExpr()));
14318 return X->getSizeExpr();
14319}
14320
14321static auto getCommonSizeModifier(const ArrayType *X, const ArrayType *Y) {
14322 assert(X->getSizeModifier() == Y->getSizeModifier());
14323 return X->getSizeModifier();
14324}
14325
14327 const ArrayType *Y) {
14328 assert(X->getIndexTypeCVRQualifiers() == Y->getIndexTypeCVRQualifiers());
14329 return X->getIndexTypeCVRQualifiers();
14330}
14331
14332// Merges two type lists such that the resulting vector will contain
14333// each type (in a canonical sense) only once, in the order they appear
14334// from X to Y. If they occur in both X and Y, the result will contain
14335// the common sugared type between them.
14336static void mergeTypeLists(const ASTContext &Ctx,
14339 llvm::DenseMap<QualType, unsigned> Found;
14340 for (auto Ts : {X, Y}) {
14341 for (QualType T : Ts) {
14342 auto Res = Found.try_emplace(Ctx.getCanonicalType(T), Out.size());
14343 if (!Res.second) {
14344 QualType &U = Out[Res.first->second];
14345 U = Ctx.getCommonSugaredType(U, T);
14346 } else {
14347 Out.emplace_back(T);
14348 }
14349 }
14350 }
14351}
14352
14353FunctionProtoType::ExceptionSpecInfo
14356 SmallVectorImpl<QualType> &ExceptionTypeStorage,
14357 bool AcceptDependent) const {
14358 ExceptionSpecificationType EST1 = ESI1.Type, EST2 = ESI2.Type;
14359
14360 // If either of them can throw anything, that is the result.
14361 for (auto I : {EST_None, EST_MSAny, EST_NoexceptFalse}) {
14362 if (EST1 == I)
14363 return ESI1;
14364 if (EST2 == I)
14365 return ESI2;
14366 }
14367
14368 // If either of them is non-throwing, the result is the other.
14369 for (auto I :
14371 if (EST1 == I)
14372 return ESI2;
14373 if (EST2 == I)
14374 return ESI1;
14375 }
14376
14377 // If we're left with value-dependent computed noexcept expressions, we're
14378 // stuck. Before C++17, we can just drop the exception specification entirely,
14379 // since it's not actually part of the canonical type. And this should never
14380 // happen in C++17, because it would mean we were computing the composite
14381 // pointer type of dependent types, which should never happen.
14382 if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) {
14383 assert(AcceptDependent &&
14384 "computing composite pointer type of dependent types");
14386 }
14387
14388 // Switch over the possibilities so that people adding new values know to
14389 // update this function.
14390 switch (EST1) {
14391 case EST_None:
14392 case EST_DynamicNone:
14393 case EST_MSAny:
14394 case EST_BasicNoexcept:
14396 case EST_NoexceptFalse:
14397 case EST_NoexceptTrue:
14398 case EST_NoThrow:
14399 llvm_unreachable("These ESTs should be handled above");
14400
14401 case EST_Dynamic: {
14402 // This is the fun case: both exception specifications are dynamic. Form
14403 // the union of the two lists.
14404 assert(EST2 == EST_Dynamic && "other cases should already be handled");
14405 mergeTypeLists(*this, ExceptionTypeStorage, ESI1.Exceptions,
14406 ESI2.Exceptions);
14408 Result.Exceptions = ExceptionTypeStorage;
14409 return Result;
14410 }
14411
14412 case EST_Unevaluated:
14413 case EST_Uninstantiated:
14414 case EST_Unparsed:
14415 llvm_unreachable("shouldn't see unresolved exception specifications here");
14416 }
14417
14418 llvm_unreachable("invalid ExceptionSpecificationType");
14419}
14420
14422 Qualifiers &QX, const Type *Y,
14423 Qualifiers &QY) {
14424 Type::TypeClass TC = X->getTypeClass();
14425 assert(TC == Y->getTypeClass());
14426 switch (TC) {
14427#define UNEXPECTED_TYPE(Class, Kind) \
14428 case Type::Class: \
14429 llvm_unreachable("Unexpected " Kind ": " #Class);
14430
14431#define NON_CANONICAL_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "non-canonical")
14432#define TYPE(Class, Base)
14433#include "clang/AST/TypeNodes.inc"
14434
14435#define SUGAR_FREE_TYPE(Class) UNEXPECTED_TYPE(Class, "sugar-free")
14437 SUGAR_FREE_TYPE(DeducedTemplateSpecialization)
14438 SUGAR_FREE_TYPE(DependentBitInt)
14440 SUGAR_FREE_TYPE(ObjCInterface)
14441 SUGAR_FREE_TYPE(SubstTemplateTypeParmPack)
14442 SUGAR_FREE_TYPE(SubstBuiltinTemplatePack)
14443 SUGAR_FREE_TYPE(UnresolvedUsing)
14444 SUGAR_FREE_TYPE(HLSLAttributedResource)
14445 SUGAR_FREE_TYPE(HLSLInlineSpirv)
14446#undef SUGAR_FREE_TYPE
14447#define NON_UNIQUE_TYPE(Class) UNEXPECTED_TYPE(Class, "non-unique")
14448 NON_UNIQUE_TYPE(TypeOfExpr)
14449 NON_UNIQUE_TYPE(VariableArray)
14450#undef NON_UNIQUE_TYPE
14451
14452 UNEXPECTED_TYPE(TypeOf, "sugar")
14453
14454#undef UNEXPECTED_TYPE
14455
14456 case Type::Auto: {
14457 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
14458 assert(AX->getDeducedKind() == AY->getDeducedKind());
14459 assert(AX->getDeducedKind() != DeducedKind::Deduced);
14460 assert(AX->getKeyword() == AY->getKeyword());
14461 TemplateDecl *CD =
14462 ::getCommonDecl(AX->getTypeConstraintConcept().getAsTemplateDecl(),
14463 AY->getTypeConstraintConcept().getAsTemplateDecl());
14465 if (CD &&
14466 getCommonTemplateArguments(Ctx, As, AX->getTypeConstraintArguments(),
14467 AY->getTypeConstraintArguments())) {
14468 CD = nullptr; // The arguments differ, so make it unconstrained.
14469 As.clear();
14470 }
14471 return Ctx.getAutoType(AX->getDeducedKind(), QualType(), AX->getKeyword(),
14472 TemplateName(CD), As);
14473 }
14474 case Type::IncompleteArray: {
14475 const auto *AX = cast<IncompleteArrayType>(X),
14477 return Ctx.getIncompleteArrayType(
14478 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
14480 }
14481 case Type::DependentSizedArray: {
14482 const auto *AX = cast<DependentSizedArrayType>(X),
14484 return Ctx.getDependentSizedArrayType(
14485 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
14486 getCommonSizeExpr(Ctx, AX, AY), getCommonSizeModifier(AX, AY),
14488 }
14489 case Type::ConstantArray: {
14490 const auto *AX = cast<ConstantArrayType>(X),
14491 *AY = cast<ConstantArrayType>(Y);
14492 assert(AX->getSize() == AY->getSize());
14493 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
14494 ? AX->getSizeExpr()
14495 : nullptr;
14496 return Ctx.getConstantArrayType(
14497 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
14499 }
14500 case Type::ArrayParameter: {
14501 const auto *AX = cast<ArrayParameterType>(X),
14502 *AY = cast<ArrayParameterType>(Y);
14503 assert(AX->getSize() == AY->getSize());
14504 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
14505 ? AX->getSizeExpr()
14506 : nullptr;
14507 auto ArrayTy = Ctx.getConstantArrayType(
14508 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
14510 return Ctx.getArrayParameterType(ArrayTy);
14511 }
14512 case Type::Atomic: {
14513 const auto *AX = cast<AtomicType>(X), *AY = cast<AtomicType>(Y);
14514 return Ctx.getAtomicType(
14515 Ctx.getCommonSugaredType(AX->getValueType(), AY->getValueType()));
14516 }
14517 case Type::Complex: {
14518 const auto *CX = cast<ComplexType>(X), *CY = cast<ComplexType>(Y);
14519 return Ctx.getComplexType(getCommonArrayElementType(Ctx, CX, QX, CY, QY));
14520 }
14521 case Type::Pointer: {
14522 const auto *PX = cast<PointerType>(X), *PY = cast<PointerType>(Y);
14523 return Ctx.getPointerType(getCommonPointeeType(Ctx, PX, PY));
14524 }
14525 case Type::BlockPointer: {
14526 const auto *PX = cast<BlockPointerType>(X), *PY = cast<BlockPointerType>(Y);
14527 return Ctx.getBlockPointerType(getCommonPointeeType(Ctx, PX, PY));
14528 }
14529 case Type::ObjCObjectPointer: {
14530 const auto *PX = cast<ObjCObjectPointerType>(X),
14532 return Ctx.getObjCObjectPointerType(getCommonPointeeType(Ctx, PX, PY));
14533 }
14534 case Type::MemberPointer: {
14535 const auto *PX = cast<MemberPointerType>(X),
14536 *PY = cast<MemberPointerType>(Y);
14537 assert(declaresSameEntity(PX->getMostRecentCXXRecordDecl(),
14538 PY->getMostRecentCXXRecordDecl()));
14539 return Ctx.getMemberPointerType(
14540 getCommonPointeeType(Ctx, PX, PY),
14541 getCommonQualifier(Ctx, PX, PY, /*IsSame=*/true),
14542 PX->getMostRecentCXXRecordDecl());
14543 }
14544 case Type::LValueReference: {
14545 const auto *PX = cast<LValueReferenceType>(X),
14547 // FIXME: Preserve PointeeTypeAsWritten.
14548 return Ctx.getLValueReferenceType(getCommonPointeeType(Ctx, PX, PY),
14549 PX->isSpelledAsLValue() ||
14550 PY->isSpelledAsLValue());
14551 }
14552 case Type::RValueReference: {
14553 const auto *PX = cast<RValueReferenceType>(X),
14555 // FIXME: Preserve PointeeTypeAsWritten.
14556 return Ctx.getRValueReferenceType(getCommonPointeeType(Ctx, PX, PY));
14557 }
14558 case Type::DependentAddressSpace: {
14559 const auto *PX = cast<DependentAddressSpaceType>(X),
14561 assert(Ctx.hasSameExpr(PX->getAddrSpaceExpr(), PY->getAddrSpaceExpr()));
14562 return Ctx.getDependentAddressSpaceType(getCommonPointeeType(Ctx, PX, PY),
14563 PX->getAddrSpaceExpr(),
14564 getCommonAttrLoc(PX, PY));
14565 }
14566 case Type::FunctionNoProto: {
14567 const auto *FX = cast<FunctionNoProtoType>(X),
14569 assert(FX->getExtInfo() == FY->getExtInfo());
14570 return Ctx.getFunctionNoProtoType(
14571 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType()),
14572 FX->getExtInfo());
14573 }
14574 case Type::FunctionProto: {
14575 const auto *FX = cast<FunctionProtoType>(X),
14576 *FY = cast<FunctionProtoType>(Y);
14577 FunctionProtoType::ExtProtoInfo EPIX = FX->getExtProtoInfo(),
14578 EPIY = FY->getExtProtoInfo();
14579 assert(EPIX.ExtInfo == EPIY.ExtInfo);
14580 assert(!EPIX.ExtParameterInfos == !EPIY.ExtParameterInfos);
14581 assert(!EPIX.ExtParameterInfos ||
14582 llvm::equal(
14583 llvm::ArrayRef(EPIX.ExtParameterInfos, FX->getNumParams()),
14584 llvm::ArrayRef(EPIY.ExtParameterInfos, FY->getNumParams())));
14585 assert(EPIX.RefQualifier == EPIY.RefQualifier);
14586 assert(EPIX.TypeQuals == EPIY.TypeQuals);
14587 assert(EPIX.Variadic == EPIY.Variadic);
14588
14589 // FIXME: Can we handle an empty EllipsisLoc?
14590 // Use emtpy EllipsisLoc if X and Y differ.
14591
14592 EPIX.HasTrailingReturn = EPIX.HasTrailingReturn && EPIY.HasTrailingReturn;
14593
14594 QualType R =
14595 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType());
14596 auto P = getCommonTypes(Ctx, FX->param_types(), FY->param_types(),
14597 /*Unqualified=*/true);
14598
14599 SmallVector<QualType, 8> Exceptions;
14601 EPIX.ExceptionSpec, EPIY.ExceptionSpec, Exceptions, true);
14602 return Ctx.getFunctionType(R, P, EPIX);
14603 }
14604 case Type::ObjCObject: {
14605 const auto *OX = cast<ObjCObjectType>(X), *OY = cast<ObjCObjectType>(Y);
14606 assert(
14607 std::equal(OX->getProtocols().begin(), OX->getProtocols().end(),
14608 OY->getProtocols().begin(), OY->getProtocols().end(),
14609 [](const ObjCProtocolDecl *P0, const ObjCProtocolDecl *P1) {
14610 return P0->getCanonicalDecl() == P1->getCanonicalDecl();
14611 }) &&
14612 "protocol lists must be the same");
14613 auto TAs = getCommonTypes(Ctx, OX->getTypeArgsAsWritten(),
14614 OY->getTypeArgsAsWritten());
14615 return Ctx.getObjCObjectType(
14616 Ctx.getCommonSugaredType(OX->getBaseType(), OY->getBaseType()), TAs,
14617 OX->getProtocols(),
14618 OX->isKindOfTypeAsWritten() && OY->isKindOfTypeAsWritten());
14619 }
14620 case Type::ConstantMatrix: {
14621 const auto *MX = cast<ConstantMatrixType>(X),
14622 *MY = cast<ConstantMatrixType>(Y);
14623 assert(MX->getNumRows() == MY->getNumRows());
14624 assert(MX->getNumColumns() == MY->getNumColumns());
14625 return Ctx.getConstantMatrixType(getCommonElementType(Ctx, MX, MY),
14626 MX->getNumRows(), MX->getNumColumns());
14627 }
14628 case Type::DependentSizedMatrix: {
14629 const auto *MX = cast<DependentSizedMatrixType>(X),
14631 assert(Ctx.hasSameExpr(MX->getRowExpr(), MY->getRowExpr()));
14632 assert(Ctx.hasSameExpr(MX->getColumnExpr(), MY->getColumnExpr()));
14633 return Ctx.getDependentSizedMatrixType(
14634 getCommonElementType(Ctx, MX, MY), MX->getRowExpr(),
14635 MX->getColumnExpr(), getCommonAttrLoc(MX, MY));
14636 }
14637 case Type::Vector: {
14638 const auto *VX = cast<VectorType>(X), *VY = cast<VectorType>(Y);
14639 assert(VX->getNumElements() == VY->getNumElements());
14640 assert(VX->getVectorKind() == VY->getVectorKind());
14641 return Ctx.getVectorType(getCommonElementType(Ctx, VX, VY),
14642 VX->getNumElements(), VX->getVectorKind());
14643 }
14644 case Type::ExtVector: {
14645 const auto *VX = cast<ExtVectorType>(X), *VY = cast<ExtVectorType>(Y);
14646 assert(VX->getNumElements() == VY->getNumElements());
14647 return Ctx.getExtVectorType(getCommonElementType(Ctx, VX, VY),
14648 VX->getNumElements());
14649 }
14650 case Type::DependentSizedExtVector: {
14651 const auto *VX = cast<DependentSizedExtVectorType>(X),
14654 getCommonSizeExpr(Ctx, VX, VY),
14655 getCommonAttrLoc(VX, VY));
14656 }
14657 case Type::DependentVector: {
14658 const auto *VX = cast<DependentVectorType>(X),
14660 assert(VX->getVectorKind() == VY->getVectorKind());
14661 return Ctx.getDependentVectorType(
14662 getCommonElementType(Ctx, VX, VY), getCommonSizeExpr(Ctx, VX, VY),
14663 getCommonAttrLoc(VX, VY), VX->getVectorKind());
14664 }
14665 case Type::Enum:
14666 case Type::Record:
14667 case Type::InjectedClassName: {
14668 const auto *TX = cast<TagType>(X), *TY = cast<TagType>(Y);
14669 return Ctx.getTagType(::getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14670 ::getCommonQualifier(Ctx, TX, TY, /*IsSame=*/false),
14671 ::getCommonDeclChecked(TX->getDecl(), TY->getDecl()),
14672 /*OwnedTag=*/false);
14673 }
14674 case Type::TemplateSpecialization: {
14675 const auto *TX = cast<TemplateSpecializationType>(X),
14677 auto As = getCommonTemplateArguments(Ctx, TX->template_arguments(),
14678 TY->template_arguments());
14680 getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14681 ::getCommonTemplateNameChecked(Ctx, TX->getTemplateName(),
14682 TY->getTemplateName(),
14683 /*IgnoreDeduced=*/true),
14684 As, /*CanonicalArgs=*/{}, X->getCanonicalTypeInternal());
14685 }
14686 case Type::Decltype: {
14687 const auto *DX = cast<DecltypeType>(X);
14688 [[maybe_unused]] const auto *DY = cast<DecltypeType>(Y);
14689 assert(DX->isDependentType());
14690 assert(DY->isDependentType());
14691 assert(Ctx.hasSameExpr(DX->getUnderlyingExpr(), DY->getUnderlyingExpr()));
14692 // As Decltype is not uniqued, building a common type would be wasteful.
14693 return QualType(DX, 0);
14694 }
14695 case Type::PackIndexing: {
14696 const auto *DX = cast<PackIndexingType>(X);
14697 [[maybe_unused]] const auto *DY = cast<PackIndexingType>(Y);
14698 assert(DX->isDependentType());
14699 assert(DY->isDependentType());
14700 assert(Ctx.hasSameExpr(DX->getIndexExpr(), DY->getIndexExpr()));
14701 return QualType(DX, 0);
14702 }
14703 case Type::DependentName: {
14704 const auto *NX = cast<DependentNameType>(X),
14705 *NY = cast<DependentNameType>(Y);
14706 assert(NX->getIdentifier() == NY->getIdentifier());
14707 return Ctx.getDependentNameType(
14708 getCommonTypeKeyword(NX, NY, /*IsSame=*/true),
14709 getCommonQualifier(Ctx, NX, NY, /*IsSame=*/true), NX->getIdentifier());
14710 }
14711 case Type::OverflowBehavior: {
14712 const auto *NX = cast<OverflowBehaviorType>(X),
14714 assert(NX->getBehaviorKind() == NY->getBehaviorKind());
14715 return Ctx.getOverflowBehaviorType(
14716 NX->getBehaviorKind(),
14717 getCommonTypeWithQualifierLifting(Ctx, NX->getUnderlyingType(),
14718 NY->getUnderlyingType(), QX, QY));
14719 }
14720 case Type::UnaryTransform: {
14721 const auto *TX = cast<UnaryTransformType>(X),
14722 *TY = cast<UnaryTransformType>(Y);
14723 assert(TX->getUTTKind() == TY->getUTTKind());
14724 return Ctx.getUnaryTransformType(
14725 Ctx.getCommonSugaredType(TX->getBaseType(), TY->getBaseType()),
14726 Ctx.getCommonSugaredType(TX->getUnderlyingType(),
14727 TY->getUnderlyingType()),
14728 TX->getUTTKind());
14729 }
14730 case Type::PackExpansion: {
14731 const auto *PX = cast<PackExpansionType>(X),
14732 *PY = cast<PackExpansionType>(Y);
14733 assert(PX->getNumExpansions() == PY->getNumExpansions());
14734 return Ctx.getPackExpansionType(
14735 Ctx.getCommonSugaredType(PX->getPattern(), PY->getPattern()),
14736 PX->getNumExpansions(), false);
14737 }
14738 case Type::Pipe: {
14739 const auto *PX = cast<PipeType>(X), *PY = cast<PipeType>(Y);
14740 assert(PX->isReadOnly() == PY->isReadOnly());
14741 auto MP = PX->isReadOnly() ? &ASTContext::getReadPipeType
14743 return (Ctx.*MP)(getCommonElementType(Ctx, PX, PY));
14744 }
14745 case Type::TemplateTypeParm: {
14746 const auto *TX = cast<TemplateTypeParmType>(X),
14748 assert(TX->getDepth() == TY->getDepth());
14749 assert(TX->getIndex() == TY->getIndex());
14750 assert(TX->isParameterPack() == TY->isParameterPack());
14751 return Ctx.getTemplateTypeParmType(
14752 TX->getDepth(), TX->getIndex(), TX->isParameterPack(),
14753 getCommonDecl(TX->getDecl(), TY->getDecl()));
14754 }
14755 }
14756 llvm_unreachable("Unknown Type Class");
14757}
14758
14760 const Type *Y,
14761 SplitQualType Underlying) {
14762 Type::TypeClass TC = X->getTypeClass();
14763 if (TC != Y->getTypeClass())
14764 return QualType();
14765 switch (TC) {
14766#define UNEXPECTED_TYPE(Class, Kind) \
14767 case Type::Class: \
14768 llvm_unreachable("Unexpected " Kind ": " #Class);
14769#define TYPE(Class, Base)
14770#define DEPENDENT_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "dependent")
14771#include "clang/AST/TypeNodes.inc"
14772
14773#define CANONICAL_TYPE(Class) UNEXPECTED_TYPE(Class, "canonical")
14776 CANONICAL_TYPE(BlockPointer)
14779 CANONICAL_TYPE(ConstantArray)
14780 CANONICAL_TYPE(ArrayParameter)
14781 CANONICAL_TYPE(ConstantMatrix)
14783 CANONICAL_TYPE(ExtVector)
14784 CANONICAL_TYPE(FunctionNoProto)
14785 CANONICAL_TYPE(FunctionProto)
14786 CANONICAL_TYPE(IncompleteArray)
14787 CANONICAL_TYPE(HLSLAttributedResource)
14788 CANONICAL_TYPE(HLSLInlineSpirv)
14789 CANONICAL_TYPE(LValueReference)
14790 CANONICAL_TYPE(ObjCInterface)
14791 CANONICAL_TYPE(ObjCObject)
14792 CANONICAL_TYPE(ObjCObjectPointer)
14793 CANONICAL_TYPE(OverflowBehavior)
14797 CANONICAL_TYPE(RValueReference)
14798 CANONICAL_TYPE(VariableArray)
14800#undef CANONICAL_TYPE
14801
14802#undef UNEXPECTED_TYPE
14803
14804 case Type::Adjusted: {
14805 const auto *AX = cast<AdjustedType>(X), *AY = cast<AdjustedType>(Y);
14806 QualType OX = AX->getOriginalType(), OY = AY->getOriginalType();
14807 if (!Ctx.hasSameType(OX, OY))
14808 return QualType();
14809 // FIXME: It's inefficient to have to unify the original types.
14810 return Ctx.getAdjustedType(Ctx.getCommonSugaredType(OX, OY),
14811 Ctx.getQualifiedType(Underlying));
14812 }
14813 case Type::Decayed: {
14814 const auto *DX = cast<DecayedType>(X), *DY = cast<DecayedType>(Y);
14815 QualType OX = DX->getOriginalType(), OY = DY->getOriginalType();
14816 if (!Ctx.hasSameType(OX, OY))
14817 return QualType();
14818 // FIXME: It's inefficient to have to unify the original types.
14819 return Ctx.getDecayedType(Ctx.getCommonSugaredType(OX, OY),
14820 Ctx.getQualifiedType(Underlying));
14821 }
14822 case Type::Attributed: {
14823 const auto *AX = cast<AttributedType>(X), *AY = cast<AttributedType>(Y);
14824 AttributedType::Kind Kind = AX->getAttrKind();
14825 if (Kind != AY->getAttrKind())
14826 return QualType();
14827 QualType MX = AX->getModifiedType(), MY = AY->getModifiedType();
14828 if (!Ctx.hasSameType(MX, MY))
14829 return QualType();
14830 // FIXME: It's inefficient to have to unify the modified types.
14831 return Ctx.getAttributedType(Kind, Ctx.getCommonSugaredType(MX, MY),
14832 Ctx.getQualifiedType(Underlying),
14833 AX->getAttr());
14834 }
14835 case Type::BTFTagAttributed: {
14836 const auto *BX = cast<BTFTagAttributedType>(X);
14837 const BTFTypeTagAttr *AX = BX->getAttr();
14838 // The attribute is not uniqued, so just compare the tag.
14839 if (AX->getBTFTypeTag() !=
14840 cast<BTFTagAttributedType>(Y)->getAttr()->getBTFTypeTag())
14841 return QualType();
14842 return Ctx.getBTFTagAttributedType(AX, Ctx.getQualifiedType(Underlying));
14843 }
14844 case Type::Auto: {
14845 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
14846 assert(AX->getDeducedKind() == DeducedKind::Deduced);
14847 assert(AY->getDeducedKind() == DeducedKind::Deduced);
14848
14849 AutoTypeKeyword KW = AX->getKeyword();
14850 if (KW != AY->getKeyword())
14851 return QualType();
14852
14853 TemplateDecl *CD =
14854 ::getCommonDecl(AX->getTypeConstraintConcept().getAsTemplateDecl(),
14855 AY->getTypeConstraintConcept().getAsTemplateDecl());
14857 if (CD &&
14858 getCommonTemplateArguments(Ctx, As, AX->getTypeConstraintArguments(),
14859 AY->getTypeConstraintArguments())) {
14860 CD = nullptr; // The arguments differ, so make it unconstrained.
14861 As.clear();
14862 }
14863
14864 // Both auto types can't be dependent, otherwise they wouldn't have been
14865 // sugar. This implies they can't contain unexpanded packs either.
14867 Ctx.getQualifiedType(Underlying), AX->getKeyword(),
14868 TemplateName(CD), As);
14869 }
14870 case Type::PackIndexing:
14871 case Type::Decltype:
14872 return QualType();
14873 case Type::DeducedTemplateSpecialization:
14874 // FIXME: Try to merge these.
14875 return QualType();
14876 case Type::MacroQualified: {
14877 const auto *MX = cast<MacroQualifiedType>(X),
14878 *MY = cast<MacroQualifiedType>(Y);
14879 const IdentifierInfo *IX = MX->getMacroIdentifier();
14880 if (IX != MY->getMacroIdentifier())
14881 return QualType();
14882 return Ctx.getMacroQualifiedType(Ctx.getQualifiedType(Underlying), IX);
14883 }
14884 case Type::SubstTemplateTypeParm: {
14885 const auto *SX = cast<SubstTemplateTypeParmType>(X),
14887 Decl *CD =
14888 ::getCommonDecl(SX->getAssociatedDecl(), SY->getAssociatedDecl());
14889 if (!CD)
14890 return QualType();
14891 unsigned Index = SX->getIndex();
14892 if (Index != SY->getIndex())
14893 return QualType();
14894 auto PackIndex = SX->getPackIndex();
14895 if (PackIndex != SY->getPackIndex())
14896 return QualType();
14897 return Ctx.getSubstTemplateTypeParmType(Ctx.getQualifiedType(Underlying),
14898 CD, Index, PackIndex,
14899 SX->getFinal() && SY->getFinal());
14900 }
14901 case Type::ObjCTypeParam:
14902 // FIXME: Try to merge these.
14903 return QualType();
14904 case Type::Paren:
14905 return Ctx.getParenType(Ctx.getQualifiedType(Underlying));
14906
14907 case Type::TemplateSpecialization: {
14908 const auto *TX = cast<TemplateSpecializationType>(X),
14910 TemplateName CTN =
14911 ::getCommonTemplateName(Ctx, TX->getTemplateName(),
14912 TY->getTemplateName(), /*IgnoreDeduced=*/true);
14913 if (!CTN.getAsVoidPointer())
14914 return QualType();
14916 if (getCommonTemplateArguments(Ctx, As, TX->template_arguments(),
14917 TY->template_arguments()))
14918 return QualType();
14920 getCommonTypeKeyword(TX, TY, /*IsSame=*/false), CTN, As,
14921 /*CanonicalArgs=*/{}, Ctx.getQualifiedType(Underlying));
14922 }
14923 case Type::Typedef: {
14924 const auto *TX = cast<TypedefType>(X), *TY = cast<TypedefType>(Y);
14925 const TypedefNameDecl *CD = ::getCommonDecl(TX->getDecl(), TY->getDecl());
14926 if (!CD)
14927 return QualType();
14928 return Ctx.getTypedefType(
14929 ::getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14930 ::getCommonQualifier(Ctx, TX, TY, /*IsSame=*/false), CD,
14931 Ctx.getQualifiedType(Underlying));
14932 }
14933 case Type::TypeOf: {
14934 // The common sugar between two typeof expressions, where one is
14935 // potentially a typeof_unqual and the other is not, we unify to the
14936 // qualified type as that retains the most information along with the type.
14937 // We only return a typeof_unqual type when both types are unqual types.
14942 return Ctx.getTypeOfType(Ctx.getQualifiedType(Underlying), Kind);
14943 }
14944 case Type::TypeOfExpr:
14945 return QualType();
14946
14947 case Type::UnaryTransform: {
14948 const auto *UX = cast<UnaryTransformType>(X),
14949 *UY = cast<UnaryTransformType>(Y);
14950 UnaryTransformType::UTTKind KX = UX->getUTTKind();
14951 if (KX != UY->getUTTKind())
14952 return QualType();
14953 QualType BX = UX->getBaseType(), BY = UY->getBaseType();
14954 if (!Ctx.hasSameType(BX, BY))
14955 return QualType();
14956 // FIXME: It's inefficient to have to unify the base types.
14957 return Ctx.getUnaryTransformType(Ctx.getCommonSugaredType(BX, BY),
14958 Ctx.getQualifiedType(Underlying), KX);
14959 }
14960 case Type::Using: {
14961 const auto *UX = cast<UsingType>(X), *UY = cast<UsingType>(Y);
14962 const UsingShadowDecl *CD = ::getCommonDecl(UX->getDecl(), UY->getDecl());
14963 if (!CD)
14964 return QualType();
14965 return Ctx.getUsingType(::getCommonTypeKeyword(UX, UY, /*IsSame=*/false),
14966 ::getCommonQualifier(Ctx, UX, UY, /*IsSame=*/false),
14967 CD, Ctx.getQualifiedType(Underlying));
14968 }
14969 case Type::MemberPointer: {
14970 const auto *PX = cast<MemberPointerType>(X),
14971 *PY = cast<MemberPointerType>(Y);
14972 CXXRecordDecl *Cls = PX->getMostRecentCXXRecordDecl();
14973 assert(Cls == PY->getMostRecentCXXRecordDecl());
14974 return Ctx.getMemberPointerType(
14975 ::getCommonPointeeType(Ctx, PX, PY),
14976 ::getCommonQualifier(Ctx, PX, PY, /*IsSame=*/false), Cls);
14977 }
14978 case Type::CountAttributed: {
14979 const auto *DX = cast<CountAttributedType>(X),
14981 if (DX->isCountInBytes() != DY->isCountInBytes())
14982 return QualType();
14983 if (DX->isOrNull() != DY->isOrNull())
14984 return QualType();
14985 Expr *CEX = DX->getCountExpr();
14986 Expr *CEY = DY->getCountExpr();
14987 ArrayRef<clang::TypeCoupledDeclRefInfo> CDX = DX->getCoupledDecls();
14988 if (Ctx.hasSameExpr(CEX, CEY))
14989 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX,
14990 DX->isCountInBytes(), DX->isOrNull(),
14991 CDX);
14992 if (!CEX->isIntegerConstantExpr(Ctx) || !CEY->isIntegerConstantExpr(Ctx))
14993 return QualType();
14994 // Two declarations with the same integer constant may still differ in their
14995 // expression pointers, so we need to evaluate them.
14996 llvm::APSInt VX = *CEX->getIntegerConstantExpr(Ctx);
14997 llvm::APSInt VY = *CEY->getIntegerConstantExpr(Ctx);
14998 if (VX != VY)
14999 return QualType();
15000 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX,
15001 DX->isCountInBytes(), DX->isOrNull(),
15002 CDX);
15003 }
15004
15005 case Type::LateParsedAttr:
15006 return QualType();
15007
15008 case Type::PredefinedSugar:
15009 assert(cast<PredefinedSugarType>(X)->getKind() !=
15011 return QualType();
15012 }
15013 llvm_unreachable("Unhandled Type Class");
15014}
15015
15016static auto unwrapSugar(SplitQualType &T, Qualifiers &QTotal) {
15018 while (true) {
15019 QTotal.addConsistentQualifiers(T.Quals);
15020 QualType NT = T.Ty->getLocallyUnqualifiedSingleStepDesugaredType();
15021 if (NT == QualType(T.Ty, 0))
15022 break;
15023 R.push_back(T);
15024 T = NT.split();
15025 }
15026 return R;
15027}
15028
15030 bool Unqualified) const {
15031 assert(Unqualified ? hasSameUnqualifiedType(X, Y) : hasSameType(X, Y));
15032 if (X == Y)
15033 return X;
15034 if (!Unqualified) {
15035 if (X.isCanonical())
15036 return X;
15037 if (Y.isCanonical())
15038 return Y;
15039 }
15040
15041 SplitQualType SX = X.split(), SY = Y.split();
15042 Qualifiers QX, QY;
15043 // Desugar SX and SY, setting the sugar and qualifiers aside into Xs and Ys,
15044 // until we reach their underlying "canonical nodes". Note these are not
15045 // necessarily canonical types, as they may still have sugared properties.
15046 // QX and QY will store the sum of all qualifiers in Xs and Ys respectively.
15047 auto Xs = ::unwrapSugar(SX, QX), Ys = ::unwrapSugar(SY, QY);
15048
15049 // If this is an ArrayType, the element qualifiers are interchangeable with
15050 // the top level qualifiers.
15051 // * In case the canonical nodes are the same, the elements types are already
15052 // the same.
15053 // * Otherwise, the element types will be made the same, and any different
15054 // element qualifiers will be moved up to the top level qualifiers, per
15055 // 'getCommonArrayElementType'.
15056 // In both cases, this means there may be top level qualifiers which differ
15057 // between X and Y. If so, these differing qualifiers are redundant with the
15058 // element qualifiers, and can be removed without changing the canonical type.
15059 // The desired behaviour is the same as for the 'Unqualified' case here:
15060 // treat the redundant qualifiers as sugar, remove the ones which are not
15061 // common to both sides.
15062 bool KeepCommonQualifiers =
15064
15065 if (SX.Ty != SY.Ty) {
15066 // The canonical nodes differ. Build a common canonical node out of the two,
15067 // unifying their sugar. This may recurse back here.
15068 SX.Ty =
15069 ::getCommonNonSugarTypeNode(*this, SX.Ty, QX, SY.Ty, QY).getTypePtr();
15070 } else {
15071 // The canonical nodes were identical: We may have desugared too much.
15072 // Add any common sugar back in.
15073 while (!Xs.empty() && !Ys.empty() && Xs.back().Ty == Ys.back().Ty) {
15074 QX -= SX.Quals;
15075 QY -= SY.Quals;
15076 SX = Xs.pop_back_val();
15077 SY = Ys.pop_back_val();
15078 }
15079 }
15080 if (KeepCommonQualifiers)
15082 else
15083 assert(QX == QY);
15084
15085 // Even though the remaining sugar nodes in Xs and Ys differ, some may be
15086 // related. Walk up these nodes, unifying them and adding the result.
15087 while (!Xs.empty() && !Ys.empty()) {
15088 auto Underlying = SplitQualType(
15089 SX.Ty, Qualifiers::removeCommonQualifiers(SX.Quals, SY.Quals));
15090 SX = Xs.pop_back_val();
15091 SY = Ys.pop_back_val();
15092 SX.Ty = ::getCommonSugarTypeNode(*this, SX.Ty, SY.Ty, Underlying)
15094 // Stop at the first pair which is unrelated.
15095 if (!SX.Ty) {
15096 SX.Ty = Underlying.Ty;
15097 break;
15098 }
15099 QX -= Underlying.Quals;
15100 };
15101
15102 // Add back the missing accumulated qualifiers, which were stripped off
15103 // with the sugar nodes we could not unify.
15104 QualType R = getQualifiedType(SX.Ty, QX);
15105 assert(Unqualified ? hasSameUnqualifiedType(R, X) : hasSameType(R, X));
15106 return R;
15107}
15108
15110 assert(Ty->isFixedPointType());
15111
15113 return Ty;
15114
15115 switch (Ty->castAs<BuiltinType>()->getKind()) {
15116 default:
15117 llvm_unreachable("Not a saturated fixed point type!");
15118 case BuiltinType::SatShortAccum:
15119 return ShortAccumTy;
15120 case BuiltinType::SatAccum:
15121 return AccumTy;
15122 case BuiltinType::SatLongAccum:
15123 return LongAccumTy;
15124 case BuiltinType::SatUShortAccum:
15125 return UnsignedShortAccumTy;
15126 case BuiltinType::SatUAccum:
15127 return UnsignedAccumTy;
15128 case BuiltinType::SatULongAccum:
15129 return UnsignedLongAccumTy;
15130 case BuiltinType::SatShortFract:
15131 return ShortFractTy;
15132 case BuiltinType::SatFract:
15133 return FractTy;
15134 case BuiltinType::SatLongFract:
15135 return LongFractTy;
15136 case BuiltinType::SatUShortFract:
15137 return UnsignedShortFractTy;
15138 case BuiltinType::SatUFract:
15139 return UnsignedFractTy;
15140 case BuiltinType::SatULongFract:
15141 return UnsignedLongFractTy;
15142 }
15143}
15144
15146 assert(Ty->isFixedPointType());
15147
15148 if (Ty->isSaturatedFixedPointType()) return Ty;
15149
15150 switch (Ty->castAs<BuiltinType>()->getKind()) {
15151 default:
15152 llvm_unreachable("Not a fixed point type!");
15153 case BuiltinType::ShortAccum:
15154 return SatShortAccumTy;
15155 case BuiltinType::Accum:
15156 return SatAccumTy;
15157 case BuiltinType::LongAccum:
15158 return SatLongAccumTy;
15159 case BuiltinType::UShortAccum:
15161 case BuiltinType::UAccum:
15162 return SatUnsignedAccumTy;
15163 case BuiltinType::ULongAccum:
15165 case BuiltinType::ShortFract:
15166 return SatShortFractTy;
15167 case BuiltinType::Fract:
15168 return SatFractTy;
15169 case BuiltinType::LongFract:
15170 return SatLongFractTy;
15171 case BuiltinType::UShortFract:
15173 case BuiltinType::UFract:
15174 return SatUnsignedFractTy;
15175 case BuiltinType::ULongFract:
15177 }
15178}
15179
15181 if (LangOpts.OpenCL)
15183
15184 if (LangOpts.CUDA)
15186
15187 return getLangASFromTargetAS(AS);
15188}
15189
15191 assert(Ty->isFixedPointType());
15192
15193 const TargetInfo &Target = getTargetInfo();
15194 switch (Ty->castAs<BuiltinType>()->getKind()) {
15195 default:
15196 llvm_unreachable("Not a fixed point type!");
15197 case BuiltinType::ShortAccum:
15198 case BuiltinType::SatShortAccum:
15199 return Target.getShortAccumScale();
15200 case BuiltinType::Accum:
15201 case BuiltinType::SatAccum:
15202 return Target.getAccumScale();
15203 case BuiltinType::LongAccum:
15204 case BuiltinType::SatLongAccum:
15205 return Target.getLongAccumScale();
15206 case BuiltinType::UShortAccum:
15207 case BuiltinType::SatUShortAccum:
15208 return Target.getUnsignedShortAccumScale();
15209 case BuiltinType::UAccum:
15210 case BuiltinType::SatUAccum:
15211 return Target.getUnsignedAccumScale();
15212 case BuiltinType::ULongAccum:
15213 case BuiltinType::SatULongAccum:
15214 return Target.getUnsignedLongAccumScale();
15215 case BuiltinType::ShortFract:
15216 case BuiltinType::SatShortFract:
15217 return Target.getShortFractScale();
15218 case BuiltinType::Fract:
15219 case BuiltinType::SatFract:
15220 return Target.getFractScale();
15221 case BuiltinType::LongFract:
15222 case BuiltinType::SatLongFract:
15223 return Target.getLongFractScale();
15224 case BuiltinType::UShortFract:
15225 case BuiltinType::SatUShortFract:
15226 return Target.getUnsignedShortFractScale();
15227 case BuiltinType::UFract:
15228 case BuiltinType::SatUFract:
15229 return Target.getUnsignedFractScale();
15230 case BuiltinType::ULongFract:
15231 case BuiltinType::SatULongFract:
15232 return Target.getUnsignedLongFractScale();
15233 }
15234}
15235
15237 assert(Ty->isFixedPointType());
15238
15239 const TargetInfo &Target = getTargetInfo();
15240 switch (Ty->castAs<BuiltinType>()->getKind()) {
15241 default:
15242 llvm_unreachable("Not a fixed point type!");
15243 case BuiltinType::ShortAccum:
15244 case BuiltinType::SatShortAccum:
15245 return Target.getShortAccumIBits();
15246 case BuiltinType::Accum:
15247 case BuiltinType::SatAccum:
15248 return Target.getAccumIBits();
15249 case BuiltinType::LongAccum:
15250 case BuiltinType::SatLongAccum:
15251 return Target.getLongAccumIBits();
15252 case BuiltinType::UShortAccum:
15253 case BuiltinType::SatUShortAccum:
15254 return Target.getUnsignedShortAccumIBits();
15255 case BuiltinType::UAccum:
15256 case BuiltinType::SatUAccum:
15257 return Target.getUnsignedAccumIBits();
15258 case BuiltinType::ULongAccum:
15259 case BuiltinType::SatULongAccum:
15260 return Target.getUnsignedLongAccumIBits();
15261 case BuiltinType::ShortFract:
15262 case BuiltinType::SatShortFract:
15263 case BuiltinType::Fract:
15264 case BuiltinType::SatFract:
15265 case BuiltinType::LongFract:
15266 case BuiltinType::SatLongFract:
15267 case BuiltinType::UShortFract:
15268 case BuiltinType::SatUShortFract:
15269 case BuiltinType::UFract:
15270 case BuiltinType::SatUFract:
15271 case BuiltinType::ULongFract:
15272 case BuiltinType::SatULongFract:
15273 return 0;
15274 }
15275}
15276
15277llvm::FixedPointSemantics
15279 assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
15280 "Can only get the fixed point semantics for a "
15281 "fixed point or integer type.");
15282 if (Ty->isIntegerType())
15283 return llvm::FixedPointSemantics::GetIntegerSemantics(
15284 getIntWidth(Ty), Ty->isSignedIntegerType());
15285
15286 bool isSigned = Ty->isSignedFixedPointType();
15287 return llvm::FixedPointSemantics(
15288 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
15290 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
15291}
15292
15293llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
15294 assert(Ty->isFixedPointType());
15295 return llvm::APFixedPoint::getMax(getFixedPointSemantics(Ty));
15296}
15297
15298llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
15299 assert(Ty->isFixedPointType());
15300 return llvm::APFixedPoint::getMin(getFixedPointSemantics(Ty));
15301}
15302
15304 assert(Ty->isUnsignedFixedPointType() &&
15305 "Expected unsigned fixed point type");
15306
15307 switch (Ty->castAs<BuiltinType>()->getKind()) {
15308 case BuiltinType::UShortAccum:
15309 return ShortAccumTy;
15310 case BuiltinType::UAccum:
15311 return AccumTy;
15312 case BuiltinType::ULongAccum:
15313 return LongAccumTy;
15314 case BuiltinType::SatUShortAccum:
15315 return SatShortAccumTy;
15316 case BuiltinType::SatUAccum:
15317 return SatAccumTy;
15318 case BuiltinType::SatULongAccum:
15319 return SatLongAccumTy;
15320 case BuiltinType::UShortFract:
15321 return ShortFractTy;
15322 case BuiltinType::UFract:
15323 return FractTy;
15324 case BuiltinType::ULongFract:
15325 return LongFractTy;
15326 case BuiltinType::SatUShortFract:
15327 return SatShortFractTy;
15328 case BuiltinType::SatUFract:
15329 return SatFractTy;
15330 case BuiltinType::SatULongFract:
15331 return SatLongFractTy;
15332 default:
15333 llvm_unreachable("Unexpected unsigned fixed point type");
15334 }
15335}
15336
15337// Given a list of FMV features, return a concatenated list of the
15338// corresponding backend features (which may contain duplicates).
15339static std::vector<std::string> getFMVBackendFeaturesFor(
15340 const llvm::SmallVectorImpl<StringRef> &FMVFeatStrings) {
15341 std::vector<std::string> BackendFeats;
15342 llvm::AArch64::ExtensionSet FeatureBits;
15343 for (StringRef F : FMVFeatStrings)
15344 if (auto FMVExt = llvm::AArch64::parseFMVExtension(F))
15345 if (FMVExt->ID)
15346 FeatureBits.enable(*FMVExt->ID);
15347 FeatureBits.toLLVMFeatureList(BackendFeats);
15348 return BackendFeats;
15349}
15350
15351ParsedTargetAttr
15352ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const {
15353 assert(TD != nullptr);
15354 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(TD->getFeaturesStr());
15355
15356 llvm::erase_if(ParsedAttr.Features, [&](const std::string &Feat) {
15357 return !Target->isValidFeatureName(StringRef{Feat}.substr(1));
15358 });
15359 return ParsedAttr;
15360}
15361
15362void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
15363 const FunctionDecl *FD) const {
15364 if (FD)
15365 getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD));
15366 else
15367 Target->initFeatureMap(FeatureMap, getDiagnostics(),
15368 Target->getTargetOpts().CPU,
15369 Target->getTargetOpts().Features);
15370}
15371
15372// Fills in the supplied string map with the set of target features for the
15373// passed in function.
15374void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
15375 GlobalDecl GD) const {
15376 StringRef TargetCPU = Target->getTargetOpts().CPU;
15377 const FunctionDecl *FD = GD.getDecl()->getAsFunction();
15378 if (const auto *TD = FD->getAttr<TargetAttr>()) {
15380
15381 // Make a copy of the features as passed on the command line into the
15382 // beginning of the additional features from the function to override.
15383 // AArch64 handles command line option features in parseTargetAttr().
15384 if (!Target->getTriple().isAArch64())
15385 ParsedAttr.Features.insert(
15386 ParsedAttr.Features.begin(),
15387 Target->getTargetOpts().FeaturesAsWritten.begin(),
15388 Target->getTargetOpts().FeaturesAsWritten.end());
15389
15390 if (ParsedAttr.CPU != "" && Target->isValidCPUName(ParsedAttr.CPU))
15391 TargetCPU = ParsedAttr.CPU;
15392
15393 // Now populate the feature map, first with the TargetCPU which is either
15394 // the default or a new one from the target attribute string. Then we'll use
15395 // the passed in features (FeaturesAsWritten) along with the new ones from
15396 // the attribute.
15397 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU,
15398 ParsedAttr.Features);
15399 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
15401 Target->getCPUSpecificCPUDispatchFeatures(
15402 SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp);
15403 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
15404 Features.insert(Features.begin(),
15405 Target->getTargetOpts().FeaturesAsWritten.begin(),
15406 Target->getTargetOpts().FeaturesAsWritten.end());
15407 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15408 } else if (const auto *TC = FD->getAttr<TargetClonesAttr>()) {
15409 if (Target->getTriple().isAArch64()) {
15411 TC->getFeatures(Feats, GD.getMultiVersionIndex());
15412 std::vector<std::string> Features = getFMVBackendFeaturesFor(Feats);
15413 Features.insert(Features.begin(),
15414 Target->getTargetOpts().FeaturesAsWritten.begin(),
15415 Target->getTargetOpts().FeaturesAsWritten.end());
15416 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15417 } else if (Target->getTriple().isRISCV()) {
15418 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
15419 std::vector<std::string> Features;
15420 if (VersionStr != "default") {
15421 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(VersionStr);
15422 Features.insert(Features.begin(), ParsedAttr.Features.begin(),
15423 ParsedAttr.Features.end());
15424 }
15425 Features.insert(Features.begin(),
15426 Target->getTargetOpts().FeaturesAsWritten.begin(),
15427 Target->getTargetOpts().FeaturesAsWritten.end());
15428 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15429 } else if (Target->getTriple().isOSAIX()) {
15430 std::vector<std::string> Features;
15431 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
15432 if (VersionStr.starts_with("cpu="))
15433 TargetCPU = VersionStr.drop_front(sizeof("cpu=") - 1);
15434 else if (VersionStr != "default")
15435 Features = Target->parseTargetAttr(VersionStr).Features;
15436 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15437 } else {
15438 std::vector<std::string> Features;
15439 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
15440 if (VersionStr.starts_with("arch="))
15441 TargetCPU = VersionStr.drop_front(sizeof("arch=") - 1);
15442 else if (VersionStr != "default")
15443 Features.push_back((StringRef{"+"} + VersionStr).str());
15444 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15445 }
15446 } else if (const auto *TV = FD->getAttr<TargetVersionAttr>()) {
15447 std::vector<std::string> Features;
15448 if (Target->getTriple().isRISCV()) {
15449 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(TV->getName());
15450 Features.insert(Features.begin(), ParsedAttr.Features.begin(),
15451 ParsedAttr.Features.end());
15452 } else {
15453 assert(Target->getTriple().isAArch64());
15455 TV->getFeatures(Feats);
15456 Features = getFMVBackendFeaturesFor(Feats);
15457 }
15458 Features.insert(Features.begin(),
15459 Target->getTargetOpts().FeaturesAsWritten.begin(),
15460 Target->getTargetOpts().FeaturesAsWritten.end());
15461 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15462 } else {
15463 FeatureMap = Target->getTargetOpts().FeatureMap;
15464 }
15465}
15466
15468 CanQualType KernelNameType,
15469 const FunctionDecl *FD) {
15470 // Host and device compilation may use different ABIs and different ABIs
15471 // may allocate name mangling discriminators differently. A discriminator
15472 // override is used to ensure consistent discriminator allocation across
15473 // host and device compilation.
15474 auto DeviceDiscriminatorOverrider =
15475 [](ASTContext &Ctx, const NamedDecl *ND) -> UnsignedOrNone {
15476 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
15477 if (RD->isLambda())
15478 return RD->getDeviceLambdaManglingNumber();
15479 return std::nullopt;
15480 };
15481 std::unique_ptr<MangleContext> MC{ItaniumMangleContext::create(
15482 Context, Context.getDiagnostics(), DeviceDiscriminatorOverrider)};
15483
15484 // Construct a mangled name for the SYCL kernel caller offload entry point.
15485 // FIXME: The Itanium typeinfo mangling (_ZTS<type>) is currently used to
15486 // name the SYCL kernel caller offload entry point function. This mangling
15487 // does not suffice to clearly identify symbols that correspond to SYCL
15488 // kernel caller functions, nor is this mangling natural for targets that
15489 // use a non-Itanium ABI.
15490 std::string Buffer;
15491 Buffer.reserve(128);
15492 llvm::raw_string_ostream Out(Buffer);
15493 MC->mangleCanonicalTypeName(KernelNameType, Out);
15494 std::string KernelName = Out.str();
15495
15496 return {KernelNameType, FD, KernelName};
15497}
15498
15500 // If the function declaration to register is invalid or dependent, the
15501 // registration attempt is ignored.
15502 if (FD->isInvalidDecl() || FD->isTemplated())
15503 return;
15504
15505 const auto *SKEPAttr = FD->getAttr<SYCLKernelEntryPointAttr>();
15506 assert(SKEPAttr && "Missing sycl_kernel_entry_point attribute");
15507
15508 // Be tolerant of multiple registration attempts so long as each attempt
15509 // is for the same entity. Callers are obligated to detect and diagnose
15510 // conflicting kernel names prior to calling this function.
15511 CanQualType KernelNameType = getCanonicalType(SKEPAttr->getKernelName());
15512 auto IT = SYCLKernels.find(KernelNameType);
15513 assert((IT == SYCLKernels.end() ||
15514 declaresSameEntity(FD, IT->second.getKernelEntryPointDecl())) &&
15515 "SYCL kernel name conflict");
15516 (void)IT;
15517 SYCLKernels.insert(std::make_pair(
15518 KernelNameType, BuildSYCLKernelInfo(*this, KernelNameType, FD)));
15519}
15520
15522 CanQualType KernelNameType = getCanonicalType(T);
15523 return SYCLKernels.at(KernelNameType);
15524}
15525
15527 CanQualType KernelNameType = getCanonicalType(T);
15528 auto IT = SYCLKernels.find(KernelNameType);
15529 if (IT != SYCLKernels.end())
15530 return &IT->second;
15531 return nullptr;
15532}
15533
15535 OMPTraitInfoVector.emplace_back(new OMPTraitInfo());
15536 return *OMPTraitInfoVector.back();
15537}
15538
15541 const ASTContext::SectionInfo &Section) {
15542 if (Section.Decl)
15543 return DB << Section.Decl;
15544 return DB << "a prior #pragma section";
15545}
15546
15547bool ASTContext::mayExternalize(const Decl *D) const {
15548 bool IsInternalVar =
15549 isa<VarDecl>(D) &&
15551 bool IsExplicitDeviceVar = (D->hasAttr<CUDADeviceAttr>() &&
15552 !D->getAttr<CUDADeviceAttr>()->isImplicit()) ||
15553 (D->hasAttr<CUDAConstantAttr>() &&
15554 !D->getAttr<CUDAConstantAttr>()->isImplicit());
15555 // CUDA/HIP: managed variables need to be externalized since it is
15556 // a declaration in IR, therefore cannot have internal linkage. Kernels in
15557 // anonymous name space needs to be externalized to avoid duplicate symbols.
15558 return (IsInternalVar &&
15559 (D->hasAttr<HIPManagedAttr>() || IsExplicitDeviceVar)) ||
15560 (D->hasAttr<CUDAGlobalAttr>() &&
15562 GVA_Internal);
15563}
15564
15566 return mayExternalize(D) &&
15567 (D->hasAttr<HIPManagedAttr>() || D->hasAttr<CUDAGlobalAttr>() ||
15569}
15570
15571StringRef ASTContext::getCUIDHash() const {
15572 if (!CUIDHash.empty())
15573 return CUIDHash;
15574 if (LangOpts.CUID.empty())
15575 return StringRef();
15576 CUIDHash = llvm::utohexstr(llvm::MD5Hash(LangOpts.CUID), /*LowerCase=*/true);
15577 return CUIDHash;
15578}
15579
15580const CXXRecordDecl *
15582 assert(ThisClass);
15583 assert(ThisClass->isPolymorphic());
15584 const CXXRecordDecl *PrimaryBase = ThisClass;
15585 while (1) {
15586 assert(PrimaryBase);
15587 assert(PrimaryBase->isPolymorphic());
15588 auto &Layout = getASTRecordLayout(PrimaryBase);
15589 auto Base = Layout.getPrimaryBase();
15590 if (!Base || Base == PrimaryBase || !Base->isPolymorphic())
15591 break;
15592 PrimaryBase = Base;
15593 }
15594 return PrimaryBase;
15595}
15596
15598 StringRef MangledName) {
15599 auto *Method = cast<CXXMethodDecl>(VirtualMethodDecl.getDecl());
15600 assert(Method->isVirtual());
15601 bool DefaultIncludesPointerAuth =
15602 LangOpts.PointerAuthCalls || LangOpts.PointerAuthIntrinsics;
15603
15604 if (!DefaultIncludesPointerAuth)
15605 return true;
15606
15607 auto Existing = ThunksToBeAbbreviated.find(VirtualMethodDecl);
15608 if (Existing != ThunksToBeAbbreviated.end())
15609 return Existing->second.contains(MangledName.str());
15610
15611 std::unique_ptr<MangleContext> Mangler(createMangleContext());
15612 llvm::StringMap<llvm::SmallVector<std::string, 2>> Thunks;
15613 auto VtableContext = getVTableContext();
15614 if (const auto *ThunkInfos = VtableContext->getThunkInfo(VirtualMethodDecl)) {
15615 auto *Destructor = dyn_cast<CXXDestructorDecl>(Method);
15616 for (const auto &Thunk : *ThunkInfos) {
15617 SmallString<256> ElidedName;
15618 llvm::raw_svector_ostream ElidedNameStream(ElidedName);
15619 if (Destructor)
15620 Mangler->mangleCXXDtorThunk(Destructor, VirtualMethodDecl.getDtorType(),
15621 Thunk, /* elideOverrideInfo */ true,
15622 ElidedNameStream);
15623 else
15624 Mangler->mangleThunk(Method, Thunk, /* elideOverrideInfo */ true,
15625 ElidedNameStream);
15626 SmallString<256> MangledName;
15627 llvm::raw_svector_ostream mangledNameStream(MangledName);
15628 if (Destructor)
15629 Mangler->mangleCXXDtorThunk(Destructor, VirtualMethodDecl.getDtorType(),
15630 Thunk, /* elideOverrideInfo */ false,
15631 mangledNameStream);
15632 else
15633 Mangler->mangleThunk(Method, Thunk, /* elideOverrideInfo */ false,
15634 mangledNameStream);
15635
15636 Thunks[ElidedName].push_back(std::string(MangledName));
15637 }
15638 }
15639 llvm::StringSet<> SimplifiedThunkNames;
15640 for (auto &ThunkList : Thunks) {
15641 llvm::sort(ThunkList.second);
15642 SimplifiedThunkNames.insert(ThunkList.second[0]);
15643 }
15644 bool Result = SimplifiedThunkNames.contains(MangledName);
15645 ThunksToBeAbbreviated[VirtualMethodDecl] = std::move(SimplifiedThunkNames);
15646 return Result;
15647}
15648
15650 // Check for trivially-destructible here because non-trivially-destructible
15651 // types will always cause the type and any types derived from it to be
15652 // considered non-trivially-copyable. The same cannot be said for
15653 // trivially-copyable because deleting special members of a type derived from
15654 // a non-trivially-copyable type can cause the derived type to be considered
15655 // trivially copyable.
15656 if (getLangOpts().PointerFieldProtectionTagged)
15657 return !isa<CXXRecordDecl>(RD) ||
15658 cast<CXXRecordDecl>(RD)->hasTrivialDestructor();
15659 return true;
15660}
15661
15662static void findPFPFields(const ASTContext &Ctx, QualType Ty, CharUnits Offset,
15663 std::vector<PFPField> &Fields, bool IncludeVBases) {
15664 if (auto *AT = Ctx.getAsConstantArrayType(Ty)) {
15665 if (auto *ElemDecl = AT->getElementType()->getAsCXXRecordDecl()) {
15666 const ASTRecordLayout &ElemRL = Ctx.getASTRecordLayout(ElemDecl);
15667 for (unsigned i = 0; i != AT->getSize(); ++i)
15668 findPFPFields(Ctx, AT->getElementType(), Offset + i * ElemRL.getSize(),
15669 Fields, true);
15670 }
15671 }
15672 auto *Decl = Ty->getAsCXXRecordDecl();
15673 // isPFPType() is inherited from bases and members (including via arrays), so
15674 // we can early exit if it is false. Unions are excluded per the API
15675 // documentation.
15676 if (!Decl || !Decl->isPFPType() || Decl->isUnion())
15677 return;
15678 const ASTRecordLayout &RL = Ctx.getASTRecordLayout(Decl);
15679 for (FieldDecl *Field : Decl->fields()) {
15680 CharUnits FieldOffset =
15681 Offset +
15682 Ctx.toCharUnitsFromBits(RL.getFieldOffset(Field->getFieldIndex()));
15683 if (Ctx.isPFPField(Field))
15684 Fields.push_back({FieldOffset, Field});
15685 findPFPFields(Ctx, Field->getType(), FieldOffset, Fields,
15686 /*IncludeVBases=*/true);
15687 }
15688 // Pass false for IncludeVBases below because vbases are only included in
15689 // layout for top-level types, i.e. not bases or vbases.
15690 for (CXXBaseSpecifier &Base : Decl->bases()) {
15691 if (Base.isVirtual())
15692 continue;
15693 CharUnits BaseOffset =
15694 Offset + RL.getBaseClassOffset(Base.getType()->getAsCXXRecordDecl());
15695 findPFPFields(Ctx, Base.getType(), BaseOffset, Fields,
15696 /*IncludeVBases=*/false);
15697 }
15698 if (IncludeVBases) {
15699 for (CXXBaseSpecifier &Base : Decl->vbases()) {
15700 CharUnits BaseOffset =
15701 Offset + RL.getVBaseClassOffset(Base.getType()->getAsCXXRecordDecl());
15702 findPFPFields(Ctx, Base.getType(), BaseOffset, Fields,
15703 /*IncludeVBases=*/false);
15704 }
15705 }
15706}
15707
15708std::vector<PFPField> ASTContext::findPFPFields(QualType Ty) const {
15709 std::vector<PFPField> PFPFields;
15710 ::findPFPFields(*this, Ty, CharUnits::Zero(), PFPFields, true);
15711 return PFPFields;
15712}
15713
15715 return !findPFPFields(Ty).empty();
15716}
15717
15719 if (auto *RD = dyn_cast<CXXRecordDecl>(FD->getParent()))
15720 return RD->isPFPType() && FD->getType()->isPointerType() &&
15721 !FD->hasAttr<NoFieldProtectionAttr>();
15722 return false;
15723}
15724
15726 auto *FD = dyn_cast<FieldDecl>(VD);
15727 if (!FD)
15728 FD = cast<FieldDecl>(cast<IndirectFieldDecl>(VD)->chain().back());
15729 if (isPFPField(FD))
15731}
15732
15734 if (E->getNumComponents() == 0)
15735 return;
15736 OffsetOfNode Comp = E->getComponent(E->getNumComponents() - 1);
15737 if (Comp.getKind() != OffsetOfNode::Field)
15738 return;
15739 if (FieldDecl *FD = Comp.getField(); isPFPField(FD))
15741}
15742
15743namespace {
15744// PaddingCalculator is a utility class that calculates the padding bits in a
15745// c/c++ type. It traverses the type recursively, collecting occupied
15746// bit intervals, and then computes the padding intervals.
15747// If a byte only contains some padding bits, it gets intervals for only those
15748// bits. This is the case for bit-fields.
15749struct PaddingCalculator {
15750 PaddingCalculator(const ASTContext &Ctx) : Ctx(Ctx) {}
15751
15752 void run(QualType Ty) {
15753 OccuppiedIntervals.clear();
15754 Stack.clear();
15755
15756 TySizeInBits = Ctx.getTypeSize(Ty);
15757
15758 Stack.push_back(Data{0, Ty.getCanonicalType(), true});
15759 while (!Stack.empty()) {
15760 Data Current = Stack.back();
15761 Stack.pop_back();
15762 Visit(Current);
15763 }
15764 MergeOccuppiedIntervals();
15765 }
15766
15767 llvm::SmallVector<ASTContext::BitInterval> GetPaddingIntervals() {
15768 llvm::SmallVector<ASTContext::BitInterval> Results;
15769 if (OccuppiedIntervals.size() == 1 &&
15770 OccuppiedIntervals.front().First == 0 &&
15771 OccuppiedIntervals.front().Last == TySizeInBits) {
15772 return Results;
15773 }
15774 Results.reserve(OccuppiedIntervals.size() + 1);
15775 uint64_t CurrentPos = 0;
15776 for (const ASTContext::BitInterval &OccupiedInterval : OccuppiedIntervals) {
15777 if (OccupiedInterval.First > CurrentPos) {
15778 Results.push_back(
15779 ASTContext::BitInterval{CurrentPos, OccupiedInterval.First});
15780 }
15781 CurrentPos = OccupiedInterval.Last;
15782 }
15783 if (TySizeInBits > CurrentPos) {
15784 Results.push_back(ASTContext::BitInterval{CurrentPos, TySizeInBits});
15785 }
15786 return Results;
15787 }
15788
15789private:
15790 struct Data {
15791 uint64_t StartBitOffset;
15792 QualType Ty;
15793 bool VisitVirtualBase;
15794 };
15795
15796 // Return the number of non padding bits of a scalar type.
15797 //
15798 // The property that we specifically care about here is whether the scalar
15799 // type has padding bits, i.e. are there bits in the type which are not
15800 // specified by the ABI.
15801 //
15802 // We currently don't care about this anywhere else in clang: layout cares
15803 // about the ABI size, calling convention code cares about specific types,
15804 // but nothing cares about padding specifically. And it's not something we can
15805 // easily query from LLVM due to the type system mismatches.
15806 // DL.getTypeSizeInBits(convertTypeForLoadStore(T)) is probably close, but the
15807 // DataLayout methods aren't really designed for this usage.
15808 //
15809 // Therefore, it is better to explicitly list all the scalar types
15810 // containing padding bits that we know of, namely, _BitInt(N) and x87 long
15811 // double.
15812 //
15813 // FIXME: There are likely other scalar types we need to think about here, as
15814 // brought up in review for #215823:
15815 // - bool
15816 // - enums(both with/without fixed underlying type)
15817 // - nullptr_t
15818 // - more?
15819 uint64_t getScalarOccupiedSizeInBits(QualType Ty) const {
15820 if (const auto *BIT = Ty->getAs<BitIntType>())
15821 return BIT->getNumBits();
15822
15823 if (const auto *BT = Ty->getAs<BuiltinType>()) {
15824 if (BT->getKind() == BuiltinType::LongDouble &&
15826 &llvm::APFloat::x87DoubleExtended())
15827 return llvm::APFloat::getSizeInBits(
15829 }
15830
15831 return Ctx.getTypeSize(Ty);
15832 }
15833
15834 void Visit(const Data &D) {
15835 if (auto *AT = dyn_cast<ConstantArrayType>(D.Ty)) {
15836 VisitArray(AT, D.StartBitOffset);
15837 return;
15838 }
15839
15840 if (auto *Record = D.Ty->getAsRecordDecl()) {
15841 VisitStruct(Record, D.StartBitOffset, D.VisitVirtualBase);
15842 return;
15843 }
15844
15845 if (D.Ty->isAtomicType()) {
15846 auto Unwrapped = D;
15847 Unwrapped.Ty = D.Ty.getAtomicUnqualifiedType().getCanonicalType();
15848 Stack.push_back(Unwrapped);
15849 return;
15850 }
15851
15852 if (const auto *Complex = D.Ty->getAs<ComplexType>()) {
15853 VisitComplex(Complex, D.StartBitOffset);
15854 return;
15855 }
15856
15857 if (const auto *VT = D.Ty->getAs<clang::VectorType>()) {
15858 VisitVector(VT, D.StartBitOffset);
15859 return;
15860 }
15861
15862 if (const auto *BITy = D.Ty->getAs<BitIntType>()) {
15863 VisitBitInt(BITy, D.StartBitOffset);
15864 return;
15865 }
15866
15867 uint64_t SizeBit = getScalarOccupiedSizeInBits(D.Ty);
15868 OccuppiedIntervals.push_back(
15869 ASTContext::BitInterval{D.StartBitOffset, D.StartBitOffset + SizeBit});
15870 }
15871
15872 void VisitArray(const ConstantArrayType *AT, uint64_t StartBitOffset) {
15873 for (uint64_t ArrIndex = 0; ArrIndex < AT->getSize().getLimitedValue();
15874 ++ArrIndex) {
15875
15876 QualType ElementQualType = AT->getElementType();
15877 auto ElementSize = Ctx.getTypeSizeInChars(ElementQualType);
15878 auto ElementAlign = Ctx.getTypeAlignInChars(ElementQualType);
15879 auto Offset = ElementSize.alignTo(ElementAlign);
15880
15881 Stack.push_back(Data{
15882 StartBitOffset + ArrIndex * Offset.getQuantity() * Ctx.getCharWidth(),
15883 ElementQualType.getCanonicalType(), /*VisitVirtualBase*/ true});
15884 }
15885 }
15886
15887 void VisitStruct(const RecordDecl *R, uint64_t StartBitOffset,
15888 bool VisitVirtualBase) {
15889 const ASTRecordLayout &ASTLayout = Ctx.getASTRecordLayout(R);
15890 auto *CXXRecord = dyn_cast<CXXRecordDecl>(R);
15891
15892 unsigned PointerSizeInBits = Ctx.getTypeSize(Ctx.NullPtrTy);
15893
15894 if (CXXRecord) {
15895 if (ASTLayout.hasOwnVFPtr()) {
15896 OccuppiedIntervals.push_back(ASTContext::BitInterval{
15897 StartBitOffset, StartBitOffset + PointerSizeInBits});
15898 }
15899
15900 if (ASTLayout.hasOwnVBPtr()) {
15901 auto Offset = ASTLayout.getVBPtrOffset().getQuantity();
15902 auto StartVBPtr = StartBitOffset + Offset * Ctx.getCharWidth();
15903 OccuppiedIntervals.push_back(ASTContext::BitInterval{
15904 StartVBPtr, StartVBPtr + PointerSizeInBits});
15905 }
15906
15907 const auto VisitBase = [&ASTLayout, StartBitOffset, this](
15908 const CXXBaseSpecifier &Base, auto GetOffset) {
15909 auto *BaseRecord = Base.getType()->getAsCXXRecordDecl();
15910 if (!BaseRecord) {
15911 return;
15912 }
15913 auto BaseOffset =
15914 std::invoke(GetOffset, ASTLayout, BaseRecord).getQuantity();
15915
15916 Stack.push_back(
15917 Data{StartBitOffset + BaseOffset * Ctx.getCharWidth(),
15918 Base.getType().getCanonicalType(), /*VisitVirtualBase*/
15919 false});
15920 };
15921
15922 for (auto Base : CXXRecord->bases()) {
15923 if (!Base.isVirtual()) {
15924 VisitBase(Base, &ASTRecordLayout::getBaseClassOffset);
15925 }
15926 }
15927
15928 if (VisitVirtualBase) {
15929 for (auto VBase : CXXRecord->vbases()) {
15930 VisitBase(VBase, &ASTRecordLayout::getVBaseClassOffset);
15931 }
15932 }
15933 }
15934
15935 for (auto *Field : R->fields()) {
15936 // Treat unnamed bitfields as padding.
15937 if (Field->isUnnamedBitField())
15938 continue;
15939
15940 auto FieldOffset = ASTLayout.getFieldOffset(Field->getFieldIndex());
15941 if (Field->isBitField()) {
15942 VisitBitfield(Field, StartBitOffset + FieldOffset);
15943 } else {
15944 Stack.push_back(Data{StartBitOffset + FieldOffset,
15945 Field->getType().getCanonicalType(),
15946 /*VisitVirtualBase*/ true});
15947 }
15948 }
15949 }
15950
15951 void VisitBitfield(const FieldDecl *Field, uint64_t StartBitOffset) {
15952 assert(Field->isBitField() && !Field->isUnnamedBitField());
15953 if (Field->isZeroLengthBitField())
15954 return;
15955
15956 const uint64_t DeclaredSizeInBits = Field->getBitWidthValue();
15957
15958 // Handle over-sized bitfields:
15959 // unsigned char a : 12;
15960 // In this case, DeclaredSizeInBits is 12, but the actually occupied bit
15961 // size is 8, while the remaining 4 bits are padding.
15962 const uint64_t OccupiedSizeInBits =
15963 std::min(DeclaredSizeInBits,
15964 static_cast<uint64_t>(Ctx.getIntWidth(Field->getType())));
15965
15966 if (Ctx.getTargetInfo().isLittleEndian()) {
15967 OccuppiedIntervals.push_back(
15968 {StartBitOffset, StartBitOffset + OccupiedSizeInBits});
15969 return;
15970 }
15971
15972 // In big endian mode, the sequence of occupied bits traverses bytes in
15973 // increasing address order, just like in little endian. However, within
15974 // each byte, the traversal starts from the most significant bit. This is
15975 // where it differs from little endian.
15976 //
15977 // If the interval contains whole bytes in the middle, then for these
15978 // nothing changes, and they constitute a contiguous interval. However for
15979 // the partially occupied bytes in either end, if present, their bit
15980 // intervals need to be adjusted so that they count from the MSB instead.
15981 //
15982 // FIXME: For over-sized bitfields in BE, Clang allocates padding bits
15983 // before the occupied bits. This violates the ABI rules, which say that
15984 // padding should be allocated after, regardless of endianness (Itanium C++
15985 // ABI §2.4, II.1(b)). The current code accommodates for Clang's current
15986 // behaviour though, and bumps Start forward to skip the leading padding
15987 // bits.
15988 const uint64_t Start =
15989 StartBitOffset + DeclaredSizeInBits - OccupiedSizeInBits;
15990 const uint64_t End = Start + OccupiedSizeInBits;
15991 const uint64_t CharWidth = Ctx.getCharWidth();
15992
15993 // Special case: all the occupied bits are contained within a single byte.
15994 const uint64_t ByteStart = llvm::alignDown(Start, CharWidth);
15995 const uint64_t ByteEnd = llvm::alignTo(End, CharWidth);
15996 if (ByteStart == ByteEnd - CharWidth) {
15997 const uint64_t Length = End - Start;
15998 const uint64_t Offset = Start - ByteStart;
15999 OccuppiedIntervals.push_back(
16000 {ByteEnd - Offset - Length, ByteEnd - Offset});
16001 return;
16002 }
16003
16004 // Compute the contiguous interval in the middle, comprised of whole bytes,
16005 // if any.
16006 const uint64_t MiddleIntervalStart = llvm::alignTo(Start, CharWidth);
16007 const uint64_t MiddleIntervalEnd = llvm::alignDown(End, CharWidth);
16008 if (MiddleIntervalStart != MiddleIntervalEnd)
16009 OccuppiedIntervals.push_back({MiddleIntervalStart, MiddleIntervalEnd});
16010
16011 // Compute the partially occupied first byte's interval, if any, counting
16012 // from the MSB.
16013 if (Start != MiddleIntervalStart) {
16014 const uint64_t Length = MiddleIntervalStart - Start;
16015 OccuppiedIntervals.push_back({ByteStart, ByteStart + Length});
16016 }
16017
16018 // Compute the partially occupied last byte's interval, if any, counting
16019 // from the MSB.
16020 if (End != MiddleIntervalEnd) {
16021 const uint64_t Length = End - MiddleIntervalEnd;
16022 OccuppiedIntervals.push_back({ByteEnd - Length, ByteEnd});
16023 }
16024 }
16025
16026 void VisitComplex(const ComplexType *CT, uint64_t StartBitOffset) {
16027 QualType ElementQualType = CT->getElementType().getCanonicalType();
16028 auto ElementSize = Ctx.getTypeSizeInChars(ElementQualType);
16029 auto ElementAlign = Ctx.getTypeAlignInChars(ElementQualType);
16030 auto ImgOffset = ElementSize.alignTo(ElementAlign);
16031
16032 Stack.push_back(
16033 Data{StartBitOffset, ElementQualType, /*VisitVirtualBase*/ true});
16034 Stack.push_back(
16035 Data{StartBitOffset + ImgOffset.getQuantity() * Ctx.getCharWidth(),
16036 ElementQualType, /*VisitVirtualBase*/ true});
16037 }
16038
16039 void VisitVector(const clang::VectorType *VT, uint64_t StartBitOffset) {
16040 if (VT->isPackedVectorBoolType(Ctx)) {
16041 VisitPackedBooleanVector(VT, StartBitOffset);
16042 return;
16043 }
16044
16045 uint64_t SizeBit = getScalarOccupiedSizeInBits(VT->getElementType()) *
16046 VT->getNumElements();
16047 OccuppiedIntervals.push_back(
16048 ASTContext::BitInterval{StartBitOffset, StartBitOffset + SizeBit});
16049 }
16050
16051 /// Compute the occupied bit intervals for a BitInt.
16052 ///
16053 /// In the case of little endian, the occupied bits are always contiguous so a
16054 /// single interval is sufficient. However in big endian, the intervals can be
16055 /// disjoint.
16056 void VisitBitInt(const BitIntType *Ty, uint64_t StartBitOffset) {
16057 const uint64_t OccupiedSizeInBits = Ty->getNumBits();
16058
16059 if (Ctx.getTargetInfo().isLittleEndian()) {
16060 OccuppiedIntervals.push_back(
16061 {StartBitOffset, StartBitOffset + OccupiedSizeInBits});
16062 return;
16063 }
16064
16065 // In big endian mode, the layout of a BitInt in memory has its bytes in
16066 // reverse order, and is pictured in this order:
16067 // 1. Fully padding bytes.
16068 // 2. One partially occupied byte, with padding at the most significant
16069 // bits. ("remaining occupied bits")
16070 // 3. A sequence of fully occupied bytes up until the end of the storage.
16071 const uint64_t StorageSizeInBits = Ctx.getTypeSize(Ty);
16072 const uint64_t CharWidth = Ctx.getCharWidth();
16073 const uint64_t NumFullyPaddingBytes =
16074 (StorageSizeInBits - OccupiedSizeInBits) / CharWidth;
16075 const uint64_t NumFullyOccupiedBytes = OccupiedSizeInBits / CharWidth;
16076 const uint64_t NumRemainingOccupiedBits = OccupiedSizeInBits % CharWidth;
16077
16078 // Partially occupied byte
16079 if (NumRemainingOccupiedBits > 0)
16080 OccuppiedIntervals.push_back(
16081 {StartBitOffset + NumFullyPaddingBytes * CharWidth,
16082 StartBitOffset + NumFullyPaddingBytes * CharWidth +
16083 NumRemainingOccupiedBits});
16084
16085 // Fully occupied bytes
16086 if (NumFullyOccupiedBytes > 0)
16087 OccuppiedIntervals.push_back({StartBitOffset + StorageSizeInBits -
16088 NumFullyOccupiedBytes * CharWidth,
16089 StartBitOffset + StorageSizeInBits});
16090 }
16091
16092 void VisitPackedBooleanVector(const VectorType *VTy,
16093 uint64_t StartBitOffset) {
16094 const uint64_t CharWidth = Ctx.getCharWidth();
16095 assert(StartBitOffset % CharWidth == 0 &&
16096 "Expected aligned packed boolean vector");
16097 assert(VTy->isPackedVectorBoolType(Ctx));
16098 const uint64_t OccupiedSizeInBits = VTy->getNumElements();
16099
16100 if (Ctx.getTargetInfo().isLittleEndian()) {
16101 OccuppiedIntervals.push_back(
16102 {StartBitOffset, StartBitOffset + OccupiedSizeInBits});
16103 return;
16104 }
16105
16106 // Only the sequence of bytes containing occupied bits has its order
16107 // reversed, but the bits within each byte are still counted from the least
16108 // significant bit. So if there are fully padding bytes, they reside at the
16109 // higher addresses in both endiannesses.
16110 const uint64_t NumFullyOccupiedBytes = OccupiedSizeInBits / CharWidth;
16111 const uint64_t NumRemainingOccupiedBits = OccupiedSizeInBits % CharWidth;
16112
16113 uint64_t Start = StartBitOffset;
16114 // Partially occupied byte at the beginning
16115 if (NumRemainingOccupiedBits > 0) {
16116 const uint64_t ByteEnd = Start + CharWidth;
16117 OccuppiedIntervals.push_back({Start, Start + NumRemainingOccupiedBits});
16118 Start = ByteEnd;
16119 }
16120
16121 // The remaining fully occupied bytes form a contiguous interval
16122 if (NumFullyOccupiedBytes > 0) {
16123 OccuppiedIntervals.push_back(
16124 {Start, Start + NumFullyOccupiedBytes * CharWidth});
16125 }
16126 }
16127
16128 void MergeOccuppiedIntervals() {
16129 std::sort(OccuppiedIntervals.begin(), OccuppiedIntervals.end(),
16130 [](const ASTContext::BitInterval &lhs,
16131 const ASTContext::BitInterval &rhs) {
16132 return std::tie(lhs.First, lhs.Last) <
16133 std::tie(rhs.First, rhs.Last);
16134 });
16135
16136 llvm::SmallVector<ASTContext::BitInterval> Merged;
16137 Merged.reserve(OccuppiedIntervals.size());
16138
16139 for (const ASTContext::BitInterval &NextInterval : OccuppiedIntervals) {
16140 if (Merged.empty()) {
16141 Merged.push_back(NextInterval);
16142 continue;
16143 }
16144 auto &LastInterval = Merged.back();
16145
16146 if (NextInterval.First > LastInterval.Last) {
16147 Merged.push_back(NextInterval);
16148 } else {
16149 LastInterval.Last = std::max(LastInterval.Last, NextInterval.Last);
16150 }
16151 }
16152
16153 OccuppiedIntervals = Merged;
16154 }
16155
16156 const ASTContext &Ctx;
16157 // unsigned PointerSizeInBits;
16158 uint64_t TySizeInBits = 0;
16159 llvm::SmallVector<Data> Stack;
16160 llvm::SmallVector<ASTContext::BitInterval> OccuppiedIntervals;
16161};
16162} // namespace
16163
16164llvm::ArrayRef<ASTContext::BitInterval>
16166 Ty = Ty.getCanonicalType();
16167 auto cached = PaddingIntervalCache.find(Ty);
16168 if (cached != PaddingIntervalCache.end())
16169 return cached->second;
16170
16171 PaddingCalculator pc{*this};
16172 pc.run(Ty);
16173
16174 auto [itr, res] =
16175 PaddingIntervalCache.insert_or_assign(Ty, pc.GetPaddingIntervals());
16176 assert(res && "Failed to insert?");
16177
16178 return itr->second;
16179}
This file provides AST data structures related to concepts.
static void SortAndUniqueProtocols(SmallVectorImpl< ObjCProtocolDecl * > &Protocols)
static bool isCanonicalExceptionSpecification(const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType)
static SourceLocation getCommonAttrLoc(const T *X, const T *Y)
static auto getCanonicalTemplateArguments(const ASTContext &C, ArrayRef< TemplateArgument > Args, bool &AnyNonCanonArgs)
static char getObjCEncodingForPrimitiveType(const ASTContext *C, const BuiltinType *BT)
static bool isSameQualifier(const NestedNameSpecifier X, const NestedNameSpecifier Y)
static bool unionHasUniqueObjectRepresentations(const ASTContext &Context, const RecordDecl *RD, bool CheckIfTriviallyCopyable)
static TypedefDecl * CreateHexagonBuiltinVaListDecl(const ASTContext *Context)
#define CANONICAL_TYPE(Class)
static ElaboratedTypeKeyword getCommonTypeKeyword(const T *X, const T *Y, bool IsSame)
static Decl * getCommonDecl(Decl *X, Decl *Y)
static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context, const Decl *D, GVALinkage L)
static bool isTypeTypedefedAsBOOL(QualType T)
static void EncodeBitField(const ASTContext *Ctx, std::string &S, QualType T, const FieldDecl *FD)
static GVALinkage basicGVALinkageForVariable(const ASTContext &Context, const VarDecl *VD)
static QualType getCommonArrayElementType(const ASTContext &Ctx, const T *X, Qualifiers &QX, const T *Y, Qualifiers &QY)
#define SUGAR_FREE_TYPE(Class)
static SYCLKernelInfo BuildSYCLKernelInfo(ASTContext &Context, CanQualType KernelNameType, const FunctionDecl *FD)
static bool hasTemplateSpecializationInEncodedString(const Type *T, bool VisitBasesAndFields)
static void getIntersectionOfProtocols(ASTContext &Context, const ObjCInterfaceDecl *CommonBase, const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT, SmallVectorImpl< ObjCProtocolDecl * > &IntersectionSet)
getIntersectionOfProtocols - This routine finds the intersection of set of protocols inherited from t...
static bool areCompatMatrixTypes(const ConstantMatrixType *LHS, const ConstantMatrixType *RHS)
areCompatMatrixTypes - Return true if the two specified matrix types are compatible.
static TypedefDecl * CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context)
static bool sameObjCTypeArgs(ASTContext &ctx, const ObjCInterfaceDecl *iface, ArrayRef< QualType > lhsArgs, ArrayRef< QualType > rhsArgs, bool stripKindOf)
static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs, QualType rhs)
Determine whether the first type is a subtype of the second.
static const Type * getIntegerTypeForEnum(const EnumType *ET)
static 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:498
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:2852
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:95
Defines the clang::Module class, which describes a module in the source code.
static StringRef getTriple(const Command &Job)
Defines types useful for describing an Objective-C runtime.
*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:123
bool isMemberPointerToDerivedMember() const
Definition APValue.cpp:1101
const ValueDecl * getMemberPointerDecl() const
Definition APValue.cpp:1094
ArrayRef< const CXXRecordDecl * > getMemberPointerPath() const
Definition APValue.cpp:1108
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:239
bool getByrefLifetime(QualType Ty, Qualifiers::ObjCLifetime &Lifetime, bool &HasByrefExtendedLayout) const
Returns true, if given type has a known lifetime.
MSGuidDecl * getMSGuidDecl(MSGuidDeclParts Parts) const
Return a declaration for the global GUID object representing the given GUID value.
CanQualType AccumTy
BuiltinVectorTypeInfo getBuiltinVectorTypeInfo(const BuiltinType *VecTy) const
Returns the element type, element count and number of vectors (in case of tuple) for a builtin vector...
bool ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl, const ObjCMethodDecl *MethodImp)
CanQualType ObjCBuiltinSelTy
TranslationUnitDecl * getTranslationUnitDecl() const
const ConstantArrayType * getAsConstantArrayType(QualType T) const
CanQualType getCanonicalFunctionResultType(QualType ResultType) const
Adjust the given function result type.
QualType getAtomicType(QualType T) const
Return the uniqued reference to the atomic type for the specified type.
LangAS getOpenCLTypeAddrSpace(const Type *T) const
Get address space for OpenCL type.
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
void InitBuiltinTypes(const TargetInfo &Target, const TargetInfo *AuxTarget=nullptr)
Initialize built-in types.
ParentMapContext & getParentMapContext()
Returns the dynamic AST node parent map context.
QualType getParenType(QualType NamedType) const
size_t getSideTableAllocatedMemory() const
Return the total memory used for various side tables.
MemberSpecializationInfo * getInstantiatedFromStaticDataMember(const VarDecl *Var)
If this variable is an instantiated static data member of a class template specialization,...
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type.
CanQualType ARCUnbridgedCastTy
QualType getDependentSizedMatrixType(QualType ElementType, Expr *RowExpr, Expr *ColumnExpr, SourceLocation AttrLoc) const
Return the unique reference to the matrix type of the specified element type and size.
QualType getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr, QualType Wrapped) const
llvm::DenseMap< const Decl *, comments::FullComment * > ParsedComments
Mapping from declarations to parsed comments attached to any redeclaration.
unsigned getManglingNumber(const NamedDecl *ND, bool ForAuxTarget=false) const
CanQualType LongTy
unsigned getIntWidth(QualType T) const
CanQualType getCanonicalParamType(QualType T) const
Return the canonical parameter type corresponding to the specific potentially non-canonical one.
const FunctionType * adjustFunctionType(const FunctionType *Fn, FunctionType::ExtInfo EInfo)
Change the ExtInfo on a function type.
TemplateOrSpecializationInfo getTemplateOrSpecializationInfo(const VarDecl *Var)
CanQualType WIntTy
@ Weak
Weak definition of inline variable.
@ WeakUnknown
Weak for now, might become strong later in this TU.
bool dtorHasOperatorDelete(const CXXDestructorDecl *Dtor, OperatorDeleteKind K) const
void setObjCConstantStringInterface(ObjCInterfaceDecl *Decl)
TypedefDecl * getObjCClassDecl() const
Retrieve the typedef declaration corresponding to the predefined Objective-C 'Class' type.
TypedefNameDecl * getTypedefNameForUnnamedTagDecl(const TagDecl *TD)
TypedefDecl * getCFConstantStringDecl() const
CanQualType Int128Ty
CanQualType SatUnsignedFractTy
void setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern)
Remember that the using decl Inst is an instantiation of the using decl Pattern of a class template.
bool areCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given types are an RISC-V vector builtin type and a VectorType that is a fixed-len...
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:854
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:855
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:850
Builtin::Context & BuiltinInfo
Definition ASTContext.h:852
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:851
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.
void eraseDeclAttrs(const Decl *D)
Erase the attributes corresponding to the given declaration.
UsingEnumDecl * getInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst)
If the given using-enum decl Inst is an instantiation of another using-enum decl, return it.
RecordDecl * getCFConstantStringTagDecl() const
std::string getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const
Emit the encoded type for the function Decl into S.
TypeSourceInfo * getTemplateSpecializationTypeInfo(ElaboratedTypeKeyword Keyword, SourceLocation ElaboratedKeywordLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKeywordLoc, TemplateName T, SourceLocation TLoc, const TemplateArgumentListInfo &SpecifiedArgs, ArrayRef< TemplateArgument > CanonicalArgs, QualType Canon=QualType()) const
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:970
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:613
CanQualType UnsignedLongTy
void DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, bool leafClass, SmallVectorImpl< const ObjCIvarDecl * > &Ivars) const
DeepCollectObjCIvars - This routine first collects all declared, but not synthesized,...
bool computeBestEnumTypes(bool IsPacked, unsigned NumNegativeBits, unsigned NumPositiveBits, QualType &BestType, QualType &BestPromotionType)
Compute BestType and BestPromotionType for an enum based on the highest number of negative and positi...
llvm::APFixedPoint getFixedPointMin(QualType Ty) const
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
QualType adjustType(QualType OldType, llvm::function_ref< QualType(QualType)> Adjust) const
Rebuild a type, preserving any existing type sugar.
void addedLocalImportDecl(ImportDecl *Import)
Notify the AST context that a new import declaration has been parsed or implicitly created within thi...
const TranslationUnitKind TUKind
Definition ASTContext.h:853
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:240
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:856
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:903
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:605
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:924
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
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:969
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
void getFunctionFeatureMap(llvm::StringMap< bool > &FeatureMap, const FunctionDecl *) const
CanQualType getNSIntegerType() const
QualType getCorrespondingUnsignedType(QualType T) const
void setBlockVarCopyInit(const VarDecl *VD, Expr *CopyExpr, bool CanThrow)
Set the copy initialization expression of a block var decl.
TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin, UnresolvedSetIterator End) const
Retrieve the template name that corresponds to a non-empty lookup.
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
TemplateName getSubstTemplateTemplateParmPack(const TemplateArgument &ArgPack, Decl *AssociatedDecl, unsigned Index, bool Final) const
TargetCXXABI::Kind getCXXABIKind() const
Return the C++ ABI kind that should be used.
QualType getHLSLAttributedResourceType(QualType Wrapped, QualType Contained, const HLSLAttributedResourceType::Attributes &Attrs)
bool UnwrapSimilarTypes(QualType &T1, QualType &T2, bool AllowPiMismatch=true) const
Attempt to unwrap two types that may be similar (C++ [conv.qual]).
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
QualType getSignedSizeType() const
Return the unique signed counterpart of the integer type corresponding to size_t.
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any.
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
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.
AttrVec & getDeclAttrs(const Decl *D)
Retrieve the attributes for the given declaration.
QualType getDeducedTemplateSpecializationType(DeducedKind DK, QualType DeducedAsType, ElaboratedTypeKeyword Keyword, TemplateName Template) const
C++17 deduced class template specialization type.
CXXMethodVector::const_iterator overridden_cxx_method_iterator
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:3598
Represents a loop initializing the elements of an array.
Definition Expr.h:6018
llvm::APInt getArraySize() const
Definition Expr.h:6040
Expr * getSubExpr() const
Get the initializer to use for each array element.
Definition Expr.h:6038
Represents a constant array type that does not decay to a pointer when used as a function parameter.
Definition TypeBase.h:3983
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3813
ArraySizeModifier getSizeModifier() const
Definition TypeBase.h:3827
Qualifiers getIndexTypeQualifiers() const
Definition TypeBase.h:3831
QualType getElementType() const
Definition TypeBase.h:3825
unsigned getIndexTypeCVRQualifiers() const
Definition TypeBase.h:3835
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:6978
Expr * getPtr() const
Definition Expr.h:7009
Attr - This represents one attribute.
Definition Attr.h:46
A fixed int type of a specified bitwidth.
Definition TypeBase.h:8297
unsigned getNumBits() const
Definition TypeBase.h:8309
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition Decl.h:4810
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition Expr.h:6722
Pointer to a block type.
Definition TypeBase.h:3646
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:3241
Kind getKind() const
Definition TypeBase.h:3292
Holds information about both target-independent and target-specific builtins, allowing easy queries b...
Definition Builtins.h:236
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:2642
Represents a C++ destructor within a class.
Definition DeclCXX.h:2907
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2150
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2263
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:169
QuantityType getQuantity() const
Get the raw integer representation of this quantity.
Definition CharUnits.h:153
static 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:3355
QualType getElementType() const
Definition TypeBase.h:3365
bool hasExplicitTemplateArgs() const
Whether or not template arguments were explicitly specified in the concept reference (they might not ...
Definition ASTConcept.h:209
const ASTTemplateArgumentListInfo * getTemplateArgsAsWritten() const
Definition ASTConcept.h:203
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3851
const Expr * getSizeExpr() const
Return a pointer to the size expression.
Definition TypeBase.h:3947
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3907
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition TypeBase.h:3966
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3927
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4483
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition TypeBase.h:4505
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:4553
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition TypeBase.h:4502
Represents a sugar type with __counted_by or __sized_by annotations, including their _or_null variant...
Definition TypeBase.h:3502
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3547
Represents a pointer type decayed from an array or function type.
Definition TypeBase.h:3629
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1466
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2126
bool isFileContext() const
Definition DeclBase.h:2217
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition DeclBase.h:2142
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
void addDecl(Decl *D)
Add the declaration D into this context.
Decl::Kind getDeclKind() const
Definition DeclBase.h:2119
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1290
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:581
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:550
void addAttr(Attr *A)
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl,...
Definition DeclBase.cpp:564
bool isUnconditionallyVisible() const
Determine whether this declaration is definitely visible to name lookup, independent of whether the o...
Definition DeclBase.h:871
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:1001
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition DeclBase.h:854
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition DeclBase.cpp:273
ObjCDeclQualifier
ObjCDeclQualifier - 'Qualifiers' written next to the return and parameter types in method declaration...
Definition DeclBase.h:198
bool isInvalidDecl() const
Definition DeclBase.h:596
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:567
void setImplicit(bool I=true)
Definition DeclBase.h:602
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition DeclBase.h:1066
DeclContext * getDeclContext()
Definition DeclBase.h:456
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:935
bool hasAttr() const
Definition DeclBase.h:585
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:995
Kind getKind() const
Definition DeclBase.h:450
DeclarationNameLoc - Additional source/type location info for a declaration name.
static DeclarationNameLoc makeCXXOperatorNameLoc(SourceLocation BeginLoc, SourceLocation EndLoc)
Construct location information for a non-literal C++ operator.
The name of a declaration.
static int compare(DeclarationName LHS, DeclarationName RHS)
Represents a ValueDecl that came out of a declarator.
Definition Decl.h:781
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:810
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:4152
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4174
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:8336
Represents an array type in C++ whose size is a value-dependent expression.
Definition TypeBase.h:4102
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4131
Represents an extended vector type where either the type or size is dependent.
Definition TypeBase.h:4192
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4217
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition TypeBase.h:4575
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4595
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:6353
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:6358
Represents a vector type where either the type or size is dependent.
Definition TypeBase.h:4318
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4343
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:232
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
A dynamically typed AST node container.
Represents an enum.
Definition Decl.h:4146
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition Decl.h:4364
bool isComplete() const
Returns true if this can be considered a complete type.
Definition Decl.h:4378
EnumDecl * getDefinitionOrSelf() const
Definition Decl.h:4262
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4319
Represents an explicit instantiation of a template entity in source code.
This represents one expression.
Definition Expr.h:113
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:3128
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:178
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:448
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:195
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition Expr.cpp:4265
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:851
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on.
Definition Expr.h:224
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:3103
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:4104
QualType getType() const
Definition Expr.h:145
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition Expr.h:438
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:4358
Declaration context for names declared as extern "C" in C++.
Definition Decl.h:248
static ExternCContextDecl * Create(const ASTContext &C, TranslationUnitDecl *TU)
Definition Decl.cpp:5613
Abstract interface for external sources of AST nodes.
Represents a member of a struct/union/class.
Definition Decl.h:3295
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3398
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition Decl.cpp:4817
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition Decl.h:3380
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3531
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:4765
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
Represents a function declaration or definition.
Definition Decl.h:2059
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition Decl.h:2820
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3804
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition Decl.h:3052
bool isMSExternInline() const
The combination of the extern and inline keywords under MSVC forces the function to be required.
Definition Decl.cpp:3933
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3789
FunctionDecl * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
FunctionDecl * getDefinition()
Get the definition for this declaration.
Definition Decl.h:2396
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition Decl.cpp:4456
bool isUserProvided() const
True if this method is user-declared and was not deleted or defaulted on its first declaration.
Definition Decl.h:2537
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:4117
FunctionDecl * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
SmallVector< Conflict > Conflicts
Definition TypeBase.h:5377
static FunctionEffectSet getIntersection(FunctionEffectsRef LHS, FunctionEffectsRef RHS)
Definition Type.cpp:6039
static FunctionEffectSet getUnion(FunctionEffectsRef LHS, FunctionEffectsRef RHS, Conflicts &Errs)
Definition Type.cpp:6077
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5209
ArrayRef< EffectConditionExpr > conditions() const
Definition TypeBase.h:5243
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition TypeBase.h:4987
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:5003
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5409
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition TypeBase.h:5913
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition TypeBase.h:5716
unsigned getNumParams() const
Definition TypeBase.h:5687
QualType getParamType(unsigned i) const
Definition TypeBase.h:5689
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition Type.cpp:4224
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition TypeBase.h:5722
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5813
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5698
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5694
ArrayRef< ExtParameterInfo > getExtParameterInfos() const
Definition TypeBase.h:5882
bool hasExtParameterInfos() const
Is there any interesting extra information for any of the parameters of this function type?
Definition TypeBase.h:5878
Declaration of a template function.
A class which abstracts out some details necessary for making a call.
Definition TypeBase.h:4716
CallingConv getCC() const
Definition TypeBase.h:4775
unsigned getRegParm() const
Definition TypeBase.h:4768
bool getNoCallerSavedRegs() const
Definition TypeBase.h:4764
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4787
Interesting information about a specific parameter that can't simply be reflected in parameter's type...
Definition TypeBase.h:4631
ExtParameterInfo withIsNoEscape(bool NoEscape) const
Definition TypeBase.h:4671
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4605
ExtInfo getExtInfo() const
Definition TypeBase.h:4961
QualType getReturnType() const
Definition TypeBase.h:4945
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:5191
Represents a C array with an unspecified size.
Definition TypeBase.h:4000
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:4017
static ItaniumMangleContext * create(ASTContext &Context, DiagnosticsEngine &Diags, bool IsAux=false)
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3708
@ 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:3570
A global _GUID constant.
Definition DeclCXX.h:4451
static void Profile(llvm::FoldingSetNodeID &ID, Parts P)
Definition DeclCXX.h:4488
MSGuidDeclParts Parts
Definition DeclCXX.h:4453
Sugar type that represents a type that was qualified by a qualifier written as a macro invocation.
Definition TypeBase.h:6287
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:4454
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition TypeBase.h:4447
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3744
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3787
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:423
This represents a decl that may have a name.
Definition Decl.h:275
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:488
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:296
bool isPlaceholderVar(const LangOptions &LangOpts) const
Definition Decl.cpp:1096
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:341
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:318
bool isExternallyVisible() const
Definition Decl.h:434
Represent a C++ namespace.
Definition Decl.h:593
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:8024
ObjCInterfaceDecl * getDecl() const
Get the declaration of this interface.
Definition Type.cpp:1082
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:8080
bool isObjCQualifiedClassType() const
True if this is equivalent to 'Class.
Definition TypeBase.h:8161
const ObjCObjectPointerType * stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const
Strip off the Objective-C "kindof" type and (with it) any protocol qualifiers.
Definition Type.cpp:1089
bool isObjCQualifiedIdType() const
True if this is equivalent to 'id.
Definition TypeBase.h:8155
const ObjCObjectType * getObjectType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:8117
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition TypeBase.h:8138
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:8092
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition TypeBase.h:8132
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition Type.cpp:2009
qual_range quals() const
Definition TypeBase.h:8199
bool isObjCClassType() const
True if this is equivalent to the 'Class' type, i.e.
Definition TypeBase.h:8144
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:2571
const OffsetOfNode & getComponent(unsigned Idx) const
Definition Expr.h:2618
unsigned getNumComponents() const
Definition Expr.h:2626
Helper class for OffsetOfExpr.
Definition Expr.h:2465
@ Field
A field.
Definition Expr.h:2472
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:4416
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:3376
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:1820
ObjCDeclQualifier getObjCDeclQualifier() const
Definition Decl.h:1884
QualType getOriginalType() const
Definition Decl.cpp:2952
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:3396
QualType getPointeeType() const
Definition TypeBase.h:3406
PredefinedSugarKind Kind
Definition TypeBase.h:8350
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:8523
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition Type.cpp:3092
Qualifiers::GC getObjCGCAttr() const
Returns gc attribute of this type.
Definition TypeBase.h:8570
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8528
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:8439
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8565
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8479
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1454
QualType getCanonicalType() const
Definition TypeBase.h:8491
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8533
SplitQualType split() const
Divides a QualType into its unqualified type and a set of local qualifiers.
Definition TypeBase.h:8460
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8512
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:8496
const Type * getTypePtrOrNull() const
Definition TypeBase.h:8443
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:3235
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition TypeBase.h:8471
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:8379
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition TypeBase.h:8386
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:3726
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:4460
bool isLambda() const
Determine whether this record is a class describing a lambda function object.
Definition Decl.cpp:5311
bool hasFlexibleArrayMember() const
Definition Decl.h:4493
field_range fields() const
Definition Decl.h:4663
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition Decl.cpp:5297
RecordDecl * getMostRecentDecl()
Definition Decl.h:4486
virtual void completeDefinition()
Note that the definition of this type is now complete.
Definition Decl.cpp:5356
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition Decl.h:4644
bool field_empty() const
Definition Decl.h:4671
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:3671
QualType getPointeeType() const
Definition TypeBase.h:3693
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:1819
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:1194
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:3852
TagTypeKind TagKind
Definition Decl.h:3857
TypedefNameDecl * getTypedefNameForAnonDecl() const
Definition Decl.h:4089
void startDefinition()
Starts the definition of this tag declaration.
Definition Decl.cpp:4971
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:4964
bool isUnion() const
Definition Decl.h:4063
TagKind getTagKind() const
Definition Decl.h:4052
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Kind
The basic C++ ABI kind.
static Kind getKind(StringRef Name)
Exposes information about the current target.
Definition TargetInfo.h:226
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:852
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:745
BuiltinVaListKind
The different kinds of __builtin_va_list types defined by the target implementation.
Definition TargetInfo.h:339
@ AArch64ABIBuiltinVaList
__builtin_va_list as defined by the AArch64 ABI http://infocenter.arm.com/help/topic/com....
Definition TargetInfo.h:348
@ PowerABIBuiltinVaList
__builtin_va_list as defined by the Power ABI: https://www.power.org /resources/downloads/Power-Arch-...
Definition TargetInfo.h:353
@ AAPCSABIBuiltinVaList
__builtin_va_list as defined by ARM AAPCS ABI http://infocenter.arm.com
Definition TargetInfo.h:362
@ CharPtrBuiltinVaList
typedef char* __builtin_va_list;
Definition TargetInfo.h:341
@ VoidPtrBuiltinVaList
typedef void* __builtin_va_list;
Definition TargetInfo.h:344
@ X86_64ABIBuiltinVaList
__builtin_va_list as defined by the x86-64 ABI: http://refspecs.linuxbase.org/elf/x86_64-abi-0....
Definition TargetInfo.h:357
virtual uint64_t getNullPointerValue(LangAS AddrSpace) const
Get integer value for null pointer.
Definition TargetInfo.h:511
static bool isTypeSigned(IntType T)
Returns true if the type is signed; false otherwise.
IntType getPtrDiffType(LangAS AddrSpace) const
Definition TargetInfo.h:413
bool isLittleEndian() const
IntType getSizeType() const
Definition TargetInfo.h:394
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:972
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:753
unsigned getTargetAddressSpace(LangAS AS) const
IntType getSignedSizeType() const
Definition TargetInfo.h:395
const llvm::fltSemantics & getLongDoubleFormat() const
Definition TargetInfo.h:803
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:227
Expr * getImmediatelyDeclaredConstraint() const
Get the immediately-declared constraint expression introduced by this type-constraint,...
Definition ASTConcept.h:244
TemplateName getNamedConcept() const
Definition ASTConcept.h:254
ConceptReference * getConceptReference() const
Definition ASTConcept.h:248
Represents a declaration of a type.
Definition Decl.h:3648
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:6319
A container of type source information.
Definition TypeBase.h:8410
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:8696
bool isVoidType() const
Definition TypeBase.h:9048
bool isObjCBuiltinType() const
Definition TypeBase.h:8906
bool isPackedVectorBoolType(const ASTContext &ctx) const
Definition Type.cpp:540
QualType getRVVEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an RVV builtin type.
Definition Type.cpp:2897
bool isIncompleteArrayType() const
Definition TypeBase.h:8783
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2390
bool isFloat16Type() const
Definition TypeBase.h:9057
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:8779
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:2643
bool isArrayType() const
Definition TypeBase.h:8775
bool isCharType() const
Definition Type.cpp:2317
bool isPointerType() const
Definition TypeBase.h:8676
TagDecl * castAsTagDecl() const
Definition Type.h:69
bool isArrayParameterType() const
Definition TypeBase.h:8791
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9092
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9342
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:9136
bool isEnumeralType() const
Definition TypeBase.h:8807
bool isObjCQualifiedIdType() const
Definition TypeBase.h:8876
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:883
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9170
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition TypeBase.h:2976
bool isBitIntType() const
Definition TypeBase.h:8951
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8799
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2859
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9108
bool isHalfType() const
Definition TypeBase.h:9052
bool isSaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9124
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:3196
@ 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:8888
bool isOverflowBehaviorType() const
Definition TypeBase.h:8847
bool isUnsaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9132
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9328
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:2653
bool isFunctionType() const
Definition TypeBase.h:8672
bool isObjCObjectPointerType() const
Definition TypeBase.h:8855
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:9150
bool isVectorType() const
Definition TypeBase.h:8815
bool isObjCClassType() const
Definition TypeBase.h:8894
bool isRVVVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'riscv_rvv_vector_bits' type attribute,...
Definition Type.cpp:2879
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition Type.cpp:2814
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2998
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:2458
bool isAnyPointerType() const
Definition TypeBase.h:8684
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:9275
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition Type.cpp:784
bool isNullPtrType() const
Definition TypeBase.h:9085
bool isRecordType() const
Definition TypeBase.h:8803
bool isObjCRetainableType() const
Definition Type.cpp:5593
NullabilityKindOrNone getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5312
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition Decl.h:3802
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition Decl.cpp:5831
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3697
QualType getUnderlyingType() const
Definition Decl.h:3752
static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TypedefNameDecl *Decl, QualType Underlying)
Definition TypeBase.h:6263
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2288
Opcode getOpcode() const
Definition Expr.h:2324
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
Definition DeclCXX.h:4508
static void Profile(llvm::FoldingSetNodeID &ID, QualType Ty, const APValue &APVal)
Definition DeclCXX.h:4536
The iterator over UnresolvedSets.
Represents the dependent type named by a dependently-scoped typename using declaration,...
Definition TypeBase.h:6124
static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const UnresolvedUsingTypenameDecl *D)
Definition TypeBase.h:6161
Represents a dependent using declaration which was marked with typename.
Definition DeclCXX.h:4067
UnresolvedUsingTypenameDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this declaration.
Definition DeclCXX.h:4132
Represents a C++ using-enum-declaration.
Definition DeclCXX.h:3822
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3429
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition DeclCXX.h:3493
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:6201
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:713
void setType(QualType newType)
Definition Decl.h:725
QualType getType() const
Definition Decl.h:724
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition Decl.cpp:5646
void clear()
Definition Value.cpp:217
Represents a variable declaration or definition.
Definition Decl.h:933
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition Decl.cpp:2780
bool hasInit() const
Definition Decl.cpp:2378
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:2441
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1307
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:1215
bool isInline() const
Whether this variable is (C++1z) inline.
Definition Decl.h:1576
@ DeclarationOnly
This declaration is only a declaration.
Definition Decl.h:1319
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition Decl.cpp:2355
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:2749
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:4057
Expr * getSizeExpr() const
Definition TypeBase.h:4071
Represents a GCC generic vector type.
Definition TypeBase.h:4266
unsigned getNumElements() const
Definition TypeBase.h:4281
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:4290
VectorKind getVectorKind() const
Definition TypeBase.h:4286
QualType getElementType() const
Definition TypeBase.h:4280
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:48
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:212
@ OCLTK_ReserveID
Definition TargetInfo.h:219
@ OCLTK_Sampler
Definition TargetInfo.h:220
@ OCLTK_Pipe
Definition TargetInfo.h:217
@ OCLTK_ClkEvent
Definition TargetInfo.h:214
@ OCLTK_Event
Definition TargetInfo.h:215
@ OCLTK_Default
Definition TargetInfo.h:213
@ OCLTK_Queue
Definition TargetInfo.h:218
constexpr llvm::StringLiteral VTTVTablePointerDiscriminatorSuffix
FunctionType::ExtInfo getFunctionExtInfo(const Type &t)
Definition TypeBase.h:8574
Stmt Stmt * Callback
Definition StmtOpenMP.h:919
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
NullabilityKind
Describes the nullability of a particular type.
Definition Specifiers.h:347
@ Nullable
Values of this type can be null.
Definition Specifiers.h:351
@ Unspecified
Whether values of this type can be null is (explicitly) unspecified.
Definition Specifiers.h:356
@ NonNull
Values of this type can never be null.
Definition Specifiers.h:349
@ ICIS_NoInit
No in-class initializer.
Definition Specifiers.h:273
@ TemplateName
The identifier is a template name. FIXME: Add an annotation for that.
Definition Parser.h:61
std::pair< FileID, unsigned > FileIDAndOffset
CXXABI * CreateMicrosoftCXXABI(ASTContext &Ctx)
@ Vector
'vector' clause, allowed on 'loop', Combined, and 'routine' directives.
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
TypeOfKind
The kind of 'typeof' expression we're after.
Definition TypeBase.h:919
@ AS_public
Definition Specifiers.h:125
SmallVector< Attr *, 4 > AttrVec
AttrVec - A vector of Attr, which is how they are stored on the AST.
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
@ SC_Register
Definition Specifiers.h:258
@ SC_Static
Definition Specifiers.h:253
CXXABI * CreateItaniumCXXABI(ASTContext &Ctx)
Creates an instance of a C++ ABI class.
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have.
Definition Linkage.h:24
@ External
External linkage, which indicates that the entity can be referred to from other translation units.
Definition Linkage.h:58
@ Result
The result type of a method or function.
Definition TypeBase.h:906
@ TypeAlignment
Definition TypeBase.h:77
ArraySizeModifier
Capture whether this is a normal array (e.g.
Definition TypeBase.h:3810
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:6037
@ Struct
The "struct" keyword.
Definition TypeBase.h:6034
@ Class
The "class" keyword.
Definition TypeBase.h:6043
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:491
@ 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:74
bool isPtrSizeAddressSpace(LangAS AS)
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:133
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:136
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition Specifiers.h:145
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:140
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1305
const StreamingDiagnostic & operator<<(const StreamingDiagnostic &DB, const ConceptReference *C)
Insertion operator for diagnostics.
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition Specifiers.h:189
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition Specifiers.h:207
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition Specifiers.h:203
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:199
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:195
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition Specifiers.h:192
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:279
@ CC_M68kRTD
Definition Specifiers.h:299
@ CC_X86RegCall
Definition Specifiers.h:288
@ CC_X86VectorCall
Definition Specifiers.h:284
@ CC_X86StdCall
Definition Specifiers.h:281
@ CC_X86FastCall
Definition Specifiers.h:282
@ Invariant
The parameter is invariant: must match exactly.
Definition DeclObjC.h: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:4236
@ SveFixedLengthData
is AArch64 SVE fixed-length data vector
Definition TypeBase.h:4245
@ AltiVecPixel
is AltiVec 'vector Pixel'
Definition TypeBase.h:4233
@ Generic
not a target-specific vector type
Definition TypeBase.h:4227
@ RVVFixedLengthData
is RISC-V RVV fixed-length data vector
Definition TypeBase.h:4251
@ RVVFixedLengthMask
is RISC-V RVV fixed-length mask vector
Definition TypeBase.h:4254
@ SveFixedLengthPredicate
is AArch64 SVE fixed-length predicate vector
Definition TypeBase.h:4248
U cast(CodeGen::Address addr)
Definition Address.h:327
LangAS getLangASFromTargetAS(unsigned TargetAS)
AlignRequirementKind
Definition ASTContext.h:174
@ 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:6007
@ Interface
The "__interface" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6012
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:6028
@ Struct
The "struct" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6009
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6018
@ Union
The "union" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6015
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6021
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition TypeBase.h:6025
ExceptionSpecificationType
The various types of exception specifications that exist in C++11.
@ EST_DependentNoexcept
noexcept(expression), value-dependent
@ EST_Uninstantiated
not instantiated yet
@ EST_Unparsed
not parsed yet
@ EST_NoThrow
Microsoft __declspec(nothrow) extension.
@ EST_None
no exception specification
@ EST_MSAny
Microsoft throw(...) extension.
@ EST_BasicNoexcept
noexcept
@ EST_NoexceptFalse
noexcept(expression), evals to 'false'
@ EST_Unevaluated
not evaluated yet, for special member function
@ EST_NoexceptTrue
noexcept(expression), evals to 'true'
@ EST_Dynamic
throw(T1, T2)
unsigned long uint64_t
unsigned NumTemplateArgs
The number of template arguments in TemplateArgs.
const Expr * ConstraintExpr
Definition Decl.h:89
UnsignedOrNone ArgPackSubstIndex
Definition Decl.h:90
Copy initialization expr of a __block variable and a boolean flag that indicates whether the expressi...
Definition Expr.h:6768
Expr * getCopyExpr() const
Definition Expr.h:6775
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:5466
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition TypeBase.h:5468
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition TypeBase.h:5471
Expr * NoexceptExpr
Noexcept expression, if this is a computed noexcept specification.
Definition TypeBase.h:5474
Extra information about a function prototype.
Definition TypeBase.h:5494
bool requiresFunctionProtoTypeArmAttributes() const
Definition TypeBase.h:5540
const ExtParameterInfo * ExtParameterInfos
Definition TypeBase.h:5499
bool requiresFunctionProtoTypeExtraAttributeInfo() const
Definition TypeBase.h:5544
bool requiresFunctionProtoTypeExtraBitfields() const
Definition TypeBase.h:5533
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:3511
A late-parsed attribute that will be applied as a type attribute.
Definition Parser.h:233
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:146
AlignRequirementKind AlignRequirement
Definition ASTContext.h:205
bool isAlignRequired()
Definition ASTContext.h:197
AlignRequirementKind AlignRequirement
Definition ASTContext.h:191
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